Repository navigation
Expand file tree
/
Copy path228.patch
More file actions
4049 lines (3977 loc) · 141 KB
/
Copy path228.patch
File metadata and controls
4049 lines (3977 loc) · 141 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
From 6d1f459131bfbd3117ea2cf96a32d8b472af4409 Mon Sep 17 00:00:00 2001
From: "Mr.liou" <z814241@gmail.com>
Date: Thu, 15 Jan 2026 00:24:29 +0800
Subject: [PATCH 1/8] Add defensive VCS commit handler
---
flowos/src/adapters/envoy.ts | 8 +
flowos/src/adapters/index.ts | 3 +
flowos/src/adapters/jetstream.ts | 8 +
flowos/src/adapters/k8s.ts | 9 +
flowos/src/core/config.ts | 45 ++++
flowos/src/core/defensive_client.ts | 99 ++++++++
flowos/src/core/gate.ts | 29 +++
flowos/src/core/neural_link.ts | 117 ++++++++++
flowos/src/index.ts | 343 +++++++++++++++++++++++-----
flowos/src/vcs-gate-unified.ts | 53 +++++
flowos/wrangler.toml | 4 +
11 files changed, 656 insertions(+), 62 deletions(-)
create mode 100644 flowos/src/adapters/envoy.ts
create mode 100644 flowos/src/adapters/index.ts
create mode 100644 flowos/src/adapters/jetstream.ts
create mode 100644 flowos/src/adapters/k8s.ts
create mode 100644 flowos/src/core/config.ts
create mode 100644 flowos/src/core/defensive_client.ts
create mode 100644 flowos/src/core/gate.ts
create mode 100644 flowos/src/core/neural_link.ts
create mode 100644 flowos/src/vcs-gate-unified.ts
create mode 100644 flowos/wrangler.toml
diff --git a/flowos/src/adapters/envoy.ts b/flowos/src/adapters/envoy.ts
new file mode 100644
index 0000000..ed885af
--- /dev/null
+++ b/flowos/src/adapters/envoy.ts
@@ -0,0 +1,8 @@
+export interface EnvoySignal {
+ cluster: string;
+ metadata?: Record<string, string>;
+}
+
+export interface EnvoyAdapter {
+ emit(signal: EnvoySignal): Promise<void>;
+}
diff --git a/flowos/src/adapters/index.ts b/flowos/src/adapters/index.ts
new file mode 100644
index 0000000..70d92e3
--- /dev/null
+++ b/flowos/src/adapters/index.ts
@@ -0,0 +1,3 @@
+export * from './envoy';
+export * from './k8s';
+export * from './jetstream';
diff --git a/flowos/src/adapters/jetstream.ts b/flowos/src/adapters/jetstream.ts
new file mode 100644
index 0000000..1f5d996
--- /dev/null
+++ b/flowos/src/adapters/jetstream.ts
@@ -0,0 +1,8 @@
+export interface JetStreamSignal {
+ subject: string;
+ payload: Record<string, unknown>;
+}
+
+export interface JetStreamAdapter {
+ publish(signal: JetStreamSignal): Promise<void>;
+}
diff --git a/flowos/src/adapters/k8s.ts b/flowos/src/adapters/k8s.ts
new file mode 100644
index 0000000..68701e1
--- /dev/null
+++ b/flowos/src/adapters/k8s.ts
@@ -0,0 +1,9 @@
+export interface K8sSignal {
+ namespace: string;
+ workload: string;
+ labels?: Record<string, string>;
+}
+
+export interface K8sAdapter {
+ deploy(signal: K8sSignal): Promise<void>;
+}
diff --git a/flowos/src/core/config.ts b/flowos/src/core/config.ts
new file mode 100644
index 0000000..fa12337
--- /dev/null
+++ b/flowos/src/core/config.ts
@@ -0,0 +1,45 @@
+export type ConfigSnapshot = Record<string, unknown>;
+
+export type ConfigListener = (next: ConfigSnapshot, previous: ConfigSnapshot) => void;
+
+export class ConfigManager {
+ private snapshot: ConfigSnapshot;
+ private readonly listeners = new Set<ConfigListener>();
+
+ constructor(initial: ConfigSnapshot = {}) {
+ this.snapshot = { ...initial };
+ }
+
+ get<T = unknown>(key: string, fallback?: T): T | undefined {
+ const value = this.snapshot[key];
+ if (value === undefined) return fallback;
+ return value as T;
+ }
+
+ all(): ConfigSnapshot {
+ return { ...this.snapshot };
+ }
+
+ update(partial: ConfigSnapshot): void {
+ const previous = this.snapshot;
+ this.snapshot = { ...previous, ...partial };
+ this.notify(previous);
+ }
+
+ subscribe(listener: ConfigListener): () => void {
+ this.listeners.add(listener);
+ return () => this.listeners.delete(listener);
+ }
+
+ async reload(loader: () => ConfigSnapshot | Promise<ConfigSnapshot>): Promise<ConfigSnapshot> {
+ const next = await loader();
+ this.update(next);
+ return this.all();
+ }
+
+ private notify(previous: ConfigSnapshot): void {
+ for (const listener of this.listeners) {
+ listener(this.snapshot, previous);
+ }
+ }
+}
diff --git a/flowos/src/core/defensive_client.ts b/flowos/src/core/defensive_client.ts
new file mode 100644
index 0000000..514a3f5
--- /dev/null
+++ b/flowos/src/core/defensive_client.ts
@@ -0,0 +1,99 @@
+/**
+ * 夥伴防禦性客戶端 (Partner Defensive Client)
+ * 核心原則:鎖定時間維度,確保「怎麼過去,就怎麼回來」
+ */
+
+export interface ClientConfig {
+ baseUrl: string;
+ token?: string;
+ externalVersions: {
+ github: '2022-11-28';
+ openai?: '2024-02-15-preview';
+ };
+ internalVersion: '4.0.0';
+}
+
+interface RequestInit {
+ method?: string;
+ headers?: Record<string, string>;
+ body?: string;
+}
+
+interface RequestInfo {}
+
+interface Response {
+ ok: boolean;
+ status: number;
+ statusText: string;
+ headers: { get(name: string): string | null };
+ json(): Promise<unknown>;
+}
+
+declare function fetch(input: RequestInfo | string, init?: RequestInit): Promise<Response>;
+
+export class ParticleDefensiveClient {
+ private config: ClientConfig;
+
+ constructor(config: ClientConfig) {
+ this.config = config;
+ }
+
+ /**
+ * 安全地呼叫 GitHub API (用於 VCS 系統)
+ * 應用了我們剛才討論的 Header 鎖定策略
+ */
+ async callGitHub(
+ endpoint: string,
+ method: string = 'GET',
+ body?: Record<string, unknown>,
+ ): Promise<unknown | null> {
+ const url = `${this.config.baseUrl}${endpoint}`;
+ const headers: Record<string, string> = {
+ 'X-GitHub-Api-Version': this.config.externalVersions.github,
+ Accept: 'application/vnd.github+json',
+ 'User-Agent': 'MrLiouWord-Particle-Edge/4.0.0',
+ 'Content-Type': 'application/json',
+ };
+ if (this.config.token) {
+ headers.Authorization = `Bearer ${this.config.token}`;
+ }
+
+ try {
+ const response = await fetch(url, {
+ method,
+ headers,
+ body: body ? JSON.stringify(body) : undefined,
+ });
+
+ if (
+ response.status === 400 &&
+ response.headers.get('x-github-api-version') !== this.config.externalVersions.github
+ ) {
+ console.error(
+ `⚠️ 警告:GitHub API 版本協定脫鉤。預期: ${this.config.externalVersions.github}`,
+ );
+ throw new Error('External_System_Protocol_Mismatch');
+ }
+
+ if (!response.ok) {
+ throw new Error(`GitHub Error: ${response.status} ${response.statusText}`);
+ }
+
+ return await response.json();
+ } catch (error) {
+ console.error('粒子傳輸失敗 (GitHub):', error);
+ return null;
+ }
+ }
+
+ /**
+ * 內部層級通訊 (Layer-to-Layer)
+ * 例如 L2 Router 呼叫 L5 Durable Object
+ */
+ async callInternalLayer(layer: string, path: string, payload: Record<string, unknown>): Promise<unknown> {
+ void layer;
+ void path;
+ void payload;
+ return { ok: true, note: '模擬內部通訊成功' };
+ }
+}
diff --git a/flowos/src/core/gate.ts b/flowos/src/core/gate.ts
new file mode 100644
index 0000000..948a1af
--- /dev/null
+++ b/flowos/src/core/gate.ts
@@ -0,0 +1,29 @@
+import { FlowContext } from '../types';
+
+export interface GateDecision {
+ allowed: boolean;
+ reason?: string;
+ throttleMs?: number;
+}
+
+export type GateCheck = (payload: Record<string, unknown>, context?: FlowContext) => GateDecision | null;
+
+export class FlowGate {
+ private readonly checks: GateCheck[] = [];
+
+ register(check: GateCheck): void {
+ this.checks.push(check);
+ }
+
+ evaluate(payload: Record<string, unknown>, context?: FlowContext): GateDecision {
+ for (const check of this.checks) {
+ const decision = check(payload, context);
+ if (decision) {
+ return decision;
+ }
+ }
+ return { allowed: true };
+ }
+}
+
+export class GateEngine extends FlowGate {}
diff --git a/flowos/src/core/neural_link.ts b/flowos/src/core/neural_link.ts
new file mode 100644
index 0000000..5552113
--- /dev/null
+++ b/flowos/src/core/neural_link.ts
@@ -0,0 +1,117 @@
+import { FlowContext } from '../types';
+import { now, randomId } from '../utils';
+
+export type NeuralLinkPayload = Record<string, unknown>;
+
+export interface NeuralLinkPacket {
+ id: string;
+ type: string;
+ payload: NeuralLinkPayload;
+ context?: FlowContext;
+ createdAt: number;
+}
+
+export type NeuralLinkHandler = (packet: NeuralLinkPacket) => void | Promise<void>;
+
+interface NeuralLinkEnv {
+ GITHUB_TOKEN?: string;
+}
+
+interface RequestInit {
+ method?: string;
+ headers?: Record<string, string>;
+ body?: string;
+}
+
+interface RequestInfo {}
+
+interface Response {
+ ok: boolean;
+ status: number;
+ json(): Promise<unknown>;
+}
+
+declare function fetch(input: RequestInfo | string, init?: RequestInit): Promise<Response>;
+
+export class NeuralLink {
+ private readonly handlers = new Map<string, NeuralLinkHandler[]>();
+
+ on(type: string, handler: NeuralLinkHandler): () => void {
+ const existing = this.handlers.get(type) ?? [];
+ existing.push(handler);
+ this.handlers.set(type, existing);
+ return () => this.off(type, handler);
+ }
+
+ off(type: string, handler: NeuralLinkHandler): void {
+ const existing = this.handlers.get(type);
+ if (!existing) return;
+ this.handlers.set(
+ type,
+ existing.filter((candidate) => candidate !== handler),
+ );
+ }
+
+ async transmit(type: string, payload: NeuralLinkPayload, context?: FlowContext): Promise<NeuralLinkPacket> {
+ const packet: NeuralLinkPacket = {
+ id: randomId(),
+ type,
+ payload,
+ context,
+ createdAt: now(),
+ };
+ const handlers = this.handlers.get(type) ?? [];
+ for (const handler of handlers) {
+ await handler(packet);
+ }
+ return packet;
+ }
+}
+
+export class ParticleNeuralLink {
+ constructor(
+ private readonly env: NeuralLinkEnv,
+ private readonly nodeId: string,
+ ) {}
+
+ async fireInternal(
+ stub: { fetch(input: RequestInfo, init?: RequestInit): Promise<Response> },
+ path: string,
+ payload: Record<string, unknown>,
+ ): Promise<Response> {
+ return await stub.fetch(`https://internal${path}`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', 'X-Node-Id': this.nodeId },
+ body: JSON.stringify(payload),
+ });
+ }
+
+ async fireExternal(
+ path: string,
+ method: string,
+ payload?: Record<string, unknown>,
+ ): Promise<unknown | null> {
+ const headers: Record<string, string> = {
+ 'Content-Type': 'application/json',
+ 'X-GitHub-Api-Version': '2022-11-28',
+ Accept: 'application/vnd.github+json',
+ 'X-Node-Id': this.nodeId,
+ };
+ if (this.env.GITHUB_TOKEN) {
+ headers.Authorization = `Bearer ${this.env.GITHUB_TOKEN}`;
+ }
+ const response = await fetch(`https://api.github.com${path}`, {
+ method,
+ headers,
+ body: payload ? JSON.stringify(payload) : undefined,
+ });
+ if (response.status === 400) {
+ console.warn('⚠️ GitHub API version may be unsupported or request is invalid.');
+ return null;
+ }
+ if (!response.ok) {
+ throw new Error(`External call failed: ${response.status}`);
+ }
+ return await response.json();
+ }
+}
diff --git a/flowos/src/index.ts b/flowos/src/index.ts
index 64639e5..081ff54 100644
--- a/flowos/src/index.ts
+++ b/flowos/src/index.ts
@@ -1,73 +1,292 @@
-import { FlowContext, FlowEvent, FlowSnapshot } from './types';
-import { MemoryStorage } from './storage';
-import { ParticleEngine } from './core/particles';
-import { ParticleStore } from './core/particles/store';
-import { MerkleChain } from './core/chains';
-import { SeedRegistry } from './core/seeds';
-import { PersonaRegistry } from './core/personas';
-import { FlowLaw } from './lib/flow-law';
-import { ConversationManager } from './app/conversations';
-import { ProjectRegistry } from './app/projects';
-import { ArtifactVault } from './app/artifacts';
-import { MemorySystem } from './app/memory';
-import { ToolRegistry } from './app/tools';
-import { randomId, now } from './utils';
-
-export class FlowOS {
- readonly storage: MemoryStorage;
- readonly particles: ParticleEngine;
- readonly particleStore: ParticleStore;
- readonly chain: MerkleChain;
- readonly seeds: SeedRegistry;
- readonly personas: PersonaRegistry;
- readonly flowLaw: FlowLaw;
- readonly conversations: ConversationManager;
- readonly projects: ProjectRegistry;
- readonly artifacts: ArtifactVault;
- readonly memory: MemorySystem;
- readonly tools: ToolRegistry;
-
- constructor() {
- this.storage = new MemoryStorage();
- this.particleStore = new ParticleStore();
- this.particles = new ParticleEngine(this.particleStore);
- this.chain = new MerkleChain();
- this.seeds = new SeedRegistry();
- this.personas = new PersonaRegistry();
- this.flowLaw = new FlowLaw();
- this.conversations = new ConversationManager(this.storage);
- this.projects = new ProjectRegistry(this.storage);
- this.artifacts = new ArtifactVault(this.storage);
- this.memory = new MemorySystem(this.storage);
- this.tools = new ToolRegistry();
+// MrLiouWord Particle Edge v4.0.0 (Unified ASI Node)
+// Integrate: Traffic Gate + Neural Link + Particle Core
+
+import { ParticleNeuralLink } from './core/neural_link';
+import { GateEngine } from './core/gate';
+export * from './core/defensive_client';
+
+// ============================================
+// 1. Environment Definition (per wrangler 2.json)
+// ============================================
+export interface Env {
+ MRLIOUWORD_VAULT: KVNamespace;
+ PARTICLE_AUTH_VAULT: KVNamespace;
+ GATE_CONFIG: KVNamespace;
+ DB: D1Database;
+ PARTICLES: R2Bucket;
+ GATE_ENGINE: DurableObjectNamespace;
+
+ // Secrets & Vars
+ MASTER_KEY: string;
+ GITHUB_TOKEN?: string;
+ VERSION: string;
+ ORIGIN: string;
+}
+
+// ============================================
+// 2. Core Brain (Main Entry)
+// ============================================
+export default {
+ async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
+ // A. Build neural link (Synapse)
+ const synapse = new ParticleNeuralLink(env, 'Edge-Node-L2');
+ const gateEngine = new GateEngine();
+ const url = new URL(request.url);
+ const path = url.pathname;
+
+ try {
+ // B. System heartbeat
+ if (path === '/heartbeat' || request.headers.get('X-Check-Pulse')) {
+ return Response.json({
+ status: 'ALIVE',
+ version: env.VERSION || '4.0.0',
+ origin: env.ORIGIN || 'MrLiouWord',
+ philosophy: '怎麼過去,就怎麼回來',
+ github_lock: '2022-11-28',
+ });
+ }
+
+ // C. Traffic Gate
+ if (path.startsWith('/gate/')) {
+ const gateStub = env.GATE_ENGINE.idFromName('global-gate').getStub();
+ const payload = await safeJson(request);
+ return await synapse.fireInternal(gateStub, path, payload);
+ }
+
+ // D. Core business logic
+ const memory = new Memory(env.MRLIOUWORD_VAULT);
+ const persona = new Persona(env.MRLIOUWORD_VAULT);
+ const auth = new Auth(env.PARTICLE_AUTH_VAULT || env.MRLIOUWORD_VAULT);
+ const vcs = new VersionControl(env.MRLIOUWORD_VAULT, synapse);
+
+ void auth;
+ void gateEngine;
+ void memory;
+
+ const key = request.headers.get('X-Master-Key') || url.searchParams.get('key');
+ const publicPaths = ['/', '/status', '/heartbeat', '/world/heartbeat', '/frequencies'];
+ if (
+ env.MASTER_KEY &&
+ key !== env.MASTER_KEY &&
+ !publicPaths.includes(path) &&
+ !path.startsWith('/auth/init')
+ ) {
+ return new Response(JSON.stringify({ error: 'Unauthorized', origin: env.ORIGIN }), { status: 401 });
+ }
+
+ // VCS - Sync GitHub
+ if (path === '/vcs/sync_github') {
+ const githubData = await synapse.fireExternal('/user/repos', 'GET');
+ return Response.json({ success: true, github_data: githubData });
+ }
+
+ if (path.startsWith('/vcs/')) {
+ return handleVCS(path, request, vcs);
+ }
+
+ if (path.startsWith('/r2/')) {
+ return handleR2(path, request, env);
+ }
+
+ if (path.startsWith('/persona/')) {
+ return handlePersona(path, request, persona);
+ }
+
+ return Response.json({
+ name: 'MrLiouWord Particle Edge',
+ version: env.VERSION,
+ mode: 'ASI Neural Link Active',
+ });
+ } catch (error: unknown) {
+ console.error('Critical Failure:', error);
+ return new Response(
+ JSON.stringify({
+ error: 'ASI_SYNAPSE_FAILURE',
+ message: 'Neural link severed to preserve integrity.',
+ trace: String(error),
+ }),
+ { status: 503 },
+ );
+ } finally {
+ ctx.waitUntil(Promise.resolve());
+ }
+ },
+};
+
+// ============================================
+// 3. Business Adapters
+// ============================================
+async function handleVCS(path: string, request: Request, vcs: VersionControl) {
+ const body = async () => safeJson(request);
+
+ if (path === '/vcs/init' && request.method === 'POST') return json(await vcs.init());
+ if (path === '/vcs/add' && request.method === 'POST') {
+ const b = (await body()) as { path?: string; content?: string };
+ return json(await vcs.add(b.path ?? '', b.content ?? ''));
+ }
+ if (path === '/vcs/commit' && request.method === 'POST') {
+ const b = (await body()) as { message?: string; persona_id?: string };
+ return json(await vcs.commit(b.message ?? '', b.persona_id ?? ''));
+ }
+ return json(await vcs.status());
+}
+
+async function handleR2(path: string, request: Request, env: Env) {
+ void request;
+ if (path === '/r2/list') {
+ const list = await env.PARTICLES.list({ limit: 100 });
+ return json({ count: list.objects.length, objects: list.objects });
+ }
+ return json({ error: 'R2 Path Not Found' }, 404);
+}
+
+async function handlePersona(path: string, request: Request, persona: Persona) {
+ const body = async () => safeJson(request);
+ if (path === '/persona/wake' && request.method === 'POST') {
+ const b = (await body()) as { message?: string };
+ return json(await persona.wake(b.message ?? ''));
+ }
+ return json({ personas: await persona.list() });
+}
+
+const json = (data: unknown, status = 200) =>
+ new Response(JSON.stringify(data), {
+ status,
+ headers: { 'Content-Type': 'application/json' },
+ });
+
+async function safeJson(request: Request): Promise<Record<string, unknown>> {
+ try {
+ return (await request.json()) as Record<string, unknown>;
+ } catch {
+ return {};
+ }
+}
+
+// ============================================
+// 4. Improved VersionControl (Neural Link injected)
+// ============================================
+class VersionControl {
+ constructor(
+ private kv: KVNamespace,
+ private synapse: ParticleNeuralLink,
+ ) {}
+
+ async syncToGitHub(repo: string, commitData: Record<string, unknown>) {
+ return await this.synapse.fireExternal(`/repos/${repo}/git/commits`, 'POST', commitData);
+ }
+
+ async init() {
+ return { success: true, msg: 'VCS Initialized (Stub)' };
+ }
+
+ async add(path: string, content: string) {
+ void path;
+ void content;
+ return { success: true };
+ }
+
+ async commit(msg: string, pid: string) {
+ void msg;
+ void pid;
+ return { success: true, hash: 'new_hash' };
+ }
+
+ async status() {
+ return { head: 'latest' };
}
+}
+
+// ============================================
+// 5. Other Classes (Memory, Persona, Auth)
+// ============================================
+class Memory {
+ constructor(private kv: KVNamespace) {
+ void this.kv;
+ }
+}
- createContext(partial: Partial<FlowContext> = {}): FlowContext {
- return {
- id: partial.id ?? randomId(),
- createdAt: partial.createdAt ?? now(),
- ...partial,
- };
+class Persona {
+ constructor(private kv: KVNamespace) {
+ void this.kv;
}
- dispatch(eventType: string, payload: Record<string, unknown>, context: FlowContext): FlowEvent {
- const event: FlowEvent = { id: randomId(), type: eventType, payload, createdAt: now() };
- this.chain.append(event, context);
- return event;
+ async wake(message: string) {
+ return { awakened: true, message };
}
- enforce(context?: FlowContext) {
- return this.flowLaw.evaluate(this.particles.listParticles(), context);
+ async list() {
+ return [];
}
+}
- snapshot(): FlowSnapshot {
- const snapshot = this.storage.snapshot();
- return {
- ...snapshot,
- particles: this.particles.listParticles(),
- };
+class Auth {
+ constructor(private kv: KVNamespace) {
+ void this.kv;
}
}
-export * from './types';
-export * from './utils';
+// ============================================
+// 6. Worker Runtime Types (stubs for build-time)
+// ============================================
+interface KVNamespace {
+ get(key: string): Promise<string | null>;
+ put(key: string, value: string): Promise<void>;
+}
+
+interface D1Database {
+ prepare(query: string): unknown;
+}
+
+interface R2Bucket {
+ list(options?: { limit?: number }): Promise<{ objects: Array<{ key: string }> }>;
+}
+
+interface DurableObjectNamespace {
+ idFromName(name: string): DurableObjectId;
+}
+
+interface DurableObjectId {
+ getStub(): DurableObjectStub;
+}
+
+interface DurableObjectStub {
+ fetch(input: RequestInfo, init?: RequestInit): Promise<Response>;
+}
+
+interface ExecutionContext {
+ waitUntil(promise: Promise<unknown>): void;
+}
+
+interface RequestInit {
+ method?: string;
+ headers?: Record<string, string>;
+ body?: string;
+}
+
+interface RequestInfo {}
+
+interface ResponseInit {
+ status?: number;
+ headers?: Record<string, string>;
+}
+
+type BodyInit = string;
+
+interface Headers {
+ get(name: string): string | null;
+}
+
+interface Request {
+ headers: Headers;
+ method: string;
+ url: string;
+ json(): Promise<unknown>;
+}
+
+interface Response {}
+
+declare const Response: {
+ new (body?: BodyInit | null, init?: ResponseInit): Response;
+ json(data: unknown, init?: ResponseInit): Response;
+};
diff --git a/flowos/src/vcs-gate-unified.ts b/flowos/src/vcs-gate-unified.ts
new file mode 100644
index 0000000..694437b
--- /dev/null
+++ b/flowos/src/vcs-gate-unified.ts
@@ -0,0 +1,53 @@
+import { ParticleDefensiveClient } from './core/defensive_client';
+
+export interface Env {
+ GITHUB_TOKEN?: string;
+ ENABLE_GITHUB_SYNC?: boolean;
+}
+
+interface Request {
+ json(): Promise<unknown>;
+}
+
+interface ResponseInit {
+ status?: number;
+ headers?: Record<string, string>;
+}
+
+interface Response {
+ json(): Promise<unknown>;
+}
+
+declare const Response: {
+ json(data: unknown, init?: ResponseInit): Response;
+};
+
+/**
+ * 增強版的 VCS Commit 處理器
+ */
+export async function handleVCSCommit(request: Request, env: Env): Promise<Response> {
+ const defensiveClient = new ParticleDefensiveClient({
+ baseUrl: 'https://api.github.com',
+ token: env.GITHUB_TOKEN,
+ externalVersions: { github: '2022-11-28' },
+ internalVersion: '4.0.0',
+ });
+
+ const body = (await request.json()) as { files?: unknown };
+
+ if (env.ENABLE_GITHUB_SYNC) {
+ try {
+ await defensiveClient.callGitHub('/repos/mrliou/particles/git/blobs', 'POST', {
+ content: JSON.stringify(body.files ?? {}),
+ encoding: 'utf-8',
+ });
+ } catch (error) {
+ console.warn('GitHub 同步失敗,但粒子系統保持完整', error);
+ }
+ }
+
+ return Response.json({
+ ok: true,
+ philosophy: '怎麼過去,就怎麼回來 (Defensive Mode Active)',
+ });
+}
diff --git a/flowos/wrangler.toml b/flowos/wrangler.toml
new file mode 100644
index 0000000..7ccb588
--- /dev/null
+++ b/flowos/wrangler.toml
@@ -0,0 +1,4 @@
+name = "flowos-neural-gate"
+main = "src/index.ts"
+compatibility_date = "2024-12-01"
+compatibility_flags = ["nodejs_compat"]
From 4900880bea4e26ef1b79b31fd93df172e86e6d52 Mon Sep 17 00:00:00 2001
From: Copilot <198982749+Copilot@users.noreply.github.com>
Date: Thu, 15 Jan 2026 19:29:55 +0800
Subject: [PATCH 2/8] Add particle-edge-v4: Cloudflare Workers edge node with
Hono, Zod, and UUID (#280)
* Initial plan
* Add particle-edge-v4 Cloudflare Workers project with Hono, Zod, and UUID
Co-authored-by: dofaromg <217537952+dofaromg@users.noreply.github.com>
* Update .gitignore to exclude auto-generated worker-configuration.d.ts
Co-authored-by: dofaromg <217537952+dofaromg@users.noreply.github.com>
---------
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: dofaromg <217537952+dofaromg@users.noreply.github.com>
---
particle-edge-v4/.gitignore | 40 ++++
particle-edge-v4/EXAMPLES.md | 150 ++++++++++++++
particle-edge-v4/README.md | 181 +++++++++++++++++
particle-edge-v4/package.json | 27 +++
particle-edge-v4/src/index.ts | 357 +++++++++++++++++++++++++++++++++
particle-edge-v4/tsconfig.json | 22 ++
particle-edge-v4/wrangler.toml | 41 ++++
7 files changed, 818 insertions(+)
create mode 100644 particle-edge-v4/.gitignore
create mode 100644 particle-edge-v4/EXAMPLES.md
create mode 100644 particle-edge-v4/README.md
create mode 100644 particle-edge-v4/package.json
create mode 100644 particle-edge-v4/src/index.ts
create mode 100644 particle-edge-v4/tsconfig.json
create mode 100644 particle-edge-v4/wrangler.toml
diff --git a/particle-edge-v4/.gitignore b/particle-edge-v4/.gitignore
new file mode 100644
index 0000000..f4747b1
--- /dev/null
+++ b/particle-edge-v4/.gitignore
@@ -0,0 +1,40 @@
+# Dependencies
+node_modules/
+package-lock.json
+yarn.lock
+pnpm-lock.yaml
+
+# Build outputs
+dist/
+.wrangler/
+worker/
+worker-configuration.d.ts
+
+# Environment files
+.env
+.env.local
+.dev.vars
+
+# IDE
+.vscode/
+.idea/
+*.swp
+*.swo
+*~
+
+# OS
+.DS_Store
+Thumbs.db
+
+# Logs
+*.log
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*
+
+# Testing
+coverage/
+
+# Temporary files
+*.tmp
+.tmp/
diff --git a/particle-edge-v4/EXAMPLES.md b/particle-edge-v4/EXAMPLES.md
new file mode 100644
index 0000000..aac46b6
--- /dev/null
+++ b/particle-edge-v4/EXAMPLES.md
@@ -0,0 +1,150 @@
+# Particle Edge v4 - API Examples
+
+This document provides example API calls for testing the Particle Edge v4 service.
+
+## Prerequisites
+
+Make sure the service is running:
+```bash
+npm run dev
+```
+
+## Example API Calls
+
+### 1. System Status
+
+```bash
+# Get system information
+curl http://localhost:8787/
+
+# Health check
+curl http://localhost:8787/heartbeat
+
+# Detailed health status
+curl http://localhost:8787/health
+```
+
+### 2. Particle Management
+
+```bash
+# Create a particle (requires authentication)
+curl -X POST http://localhost:8787/particles \
+ -H "Content-Type: application/json" \
+ -H "X-Master-Key: your-master-key" \
+ -d '{
+ "content": "Test particle data",
+ "metadata": {
+ "type": "test",
+ "priority": "high"
+ }
+ }'
+
+# Get a particle by ID
+curl http://localhost:8787/particles/YOUR_PARTICLE_ID \
+ -H "X-Master-Key: your-master-key"
+
+# List all particles
+curl http://localhost:8787/particles?limit=10 \
+ -H "X-Master-Key: your-master-key"
+
+# Delete a particle
+curl -X DELETE http://localhost:8787/particles/YOUR_PARTICLE_ID \
+ -H "X-Master-Key: your-master-key"
+```
+
+### 3. R2 Storage Operations
+
+```bash
+# List R2 objects
+curl http://localhost:8787/r2/list?limit=100 \
+ -H "X-Master-Key: your-master-key"
+
+# Upload to R2
+curl -X PUT http://localhost:8787/r2/test-file.txt \
+ -H "X-Master-Key: your-master-key" \
+ -H "Content-Type: text/plain" \
+ -d "This is test content"
+```
+
+### 4. Gate Engine Operations
+
+```bash
+# Register with gate
+curl -X POST http://localhost:8787/gate/register \
+ -H "Content-Type: application/json" \
+ -H "X-Master-Key: your-master-key" \
+ -d '{}'
+
+# Get gate status
+curl -X POST http://localhost:8787/gate/status \
+ -H "Content-Type: application/json" \
+ -H "X-Master-Key: your-master-key" \
+ -d '{}'
+
+# Process data through gate
+curl -X POST http://localhost:8787/gate/process \
+ -H "Content-Type: application/json" \
+ -H "X-Master-Key: your-master-key" \