@n2world/orchestrator 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. package/dist/agent-os-rd.d.ts +100 -0
  2. package/dist/agent-os-rd.js +258 -0
  3. package/dist/audit-store.d.ts +14 -0
  4. package/dist/audit-store.js +107 -0
  5. package/dist/beta-runner.d.ts +95 -0
  6. package/dist/beta-runner.js +251 -0
  7. package/dist/beta.d.ts +102 -0
  8. package/dist/beta.js +180 -0
  9. package/dist/browser-agent.d.ts +90 -0
  10. package/dist/browser-agent.js +223 -0
  11. package/dist/channel-gateway.d.ts +74 -0
  12. package/dist/channel-gateway.js +270 -0
  13. package/dist/channels.d.ts +120 -0
  14. package/dist/channels.js +432 -0
  15. package/dist/chat-store.d.ts +29 -0
  16. package/dist/chat-store.js +120 -0
  17. package/dist/cli.d.ts +2 -0
  18. package/dist/cli.js +607 -0
  19. package/dist/command-screen.d.ts +12 -0
  20. package/dist/command-screen.js +44 -0
  21. package/dist/commit-gate.d.ts +98 -0
  22. package/dist/commit-gate.js +258 -0
  23. package/dist/companion-api.d.ts +37 -0
  24. package/dist/companion-api.js +101 -0
  25. package/dist/conversation-graph.d.ts +39 -0
  26. package/dist/conversation-graph.js +92 -0
  27. package/dist/cost-estimator.d.ts +27 -0
  28. package/dist/cost-estimator.js +42 -0
  29. package/dist/cron-runner.d.ts +31 -0
  30. package/dist/cron-runner.js +46 -0
  31. package/dist/dashboard/chat.html +326 -0
  32. package/dist/dashboard/dental.html +58 -0
  33. package/dist/dashboard/freebie.png +0 -0
  34. package/dist/dashboard/icon-192.png +0 -0
  35. package/dist/dashboard/index.html +892 -0
  36. package/dist/dashboard/manifest.json +15 -0
  37. package/dist/dashboard/service-worker.js +28 -0
  38. package/dist/dashboard-server.d.ts +37 -0
  39. package/dist/dashboard-server.js +457 -0
  40. package/dist/dental-intake-service.d.ts +37 -0
  41. package/dist/dental-intake-service.js +61 -0
  42. package/dist/dental-metrics.d.ts +25 -0
  43. package/dist/dental-metrics.js +37 -0
  44. package/dist/docking.d.ts +36 -0
  45. package/dist/docking.js +73 -0
  46. package/dist/finance-mcts-candidate.d.ts +37 -0
  47. package/dist/finance-mcts-candidate.js +106 -0
  48. package/dist/finance-regulation-kr.d.ts +33 -0
  49. package/dist/finance-regulation-kr.js +104 -0
  50. package/dist/finance-workflow.d.ts +135 -0
  51. package/dist/finance-workflow.js +242 -0
  52. package/dist/gateway.d.ts +18 -0
  53. package/dist/gateway.js +123 -0
  54. package/dist/governance.d.ts +39 -0
  55. package/dist/governance.js +48 -0
  56. package/dist/governed-executor.d.ts +31 -0
  57. package/dist/governed-executor.js +63 -0
  58. package/dist/governed-llm.d.ts +41 -0
  59. package/dist/governed-llm.js +83 -0
  60. package/dist/gpu-bridge.d.ts +16 -0
  61. package/dist/gpu-bridge.js +53 -0
  62. package/dist/health.d.ts +47 -0
  63. package/dist/health.js +66 -0
  64. package/dist/identity-link.d.ts +32 -0
  65. package/dist/identity-link.js +98 -0
  66. package/dist/index.d.ts +184 -0
  67. package/dist/index.js +417 -0
  68. package/dist/integrations/emr-adapter.d.ts +41 -0
  69. package/dist/integrations/emr-adapter.js +63 -0
  70. package/dist/kakao-oauth.d.ts +16 -0
  71. package/dist/kakao-oauth.js +87 -0
  72. package/dist/knowledge-graph.d.ts +53 -0
  73. package/dist/knowledge-graph.js +156 -0
  74. package/dist/llm.d.ts +65 -0
  75. package/dist/llm.js +357 -0
  76. package/dist/mcp-client-guard.d.ts +32 -0
  77. package/dist/mcp-client-guard.js +179 -0
  78. package/dist/mcp-macaroon.d.ts +75 -0
  79. package/dist/mcp-macaroon.js +161 -0
  80. package/dist/mcts-kernel-bridge.d.ts +36 -0
  81. package/dist/mcts-kernel-bridge.js +99 -0
  82. package/dist/mcts-prior.d.ts +79 -0
  83. package/dist/mcts-prior.js +170 -0
  84. package/dist/model-router.d.ts +51 -0
  85. package/dist/model-router.js +75 -0
  86. package/dist/multi-axis-lift.d.ts +43 -0
  87. package/dist/multi-axis-lift.js +141 -0
  88. package/dist/net-guard.d.ts +39 -0
  89. package/dist/net-guard.js +141 -0
  90. package/dist/onboarding.d.ts +38 -0
  91. package/dist/onboarding.js +94 -0
  92. package/dist/oracle-anchored-search.d.ts +25 -0
  93. package/dist/oracle-anchored-search.js +50 -0
  94. package/dist/oracle.d.ts +22 -0
  95. package/dist/oracle.js +116 -0
  96. package/dist/p6-governance.d.ts +150 -0
  97. package/dist/p6-governance.js +252 -0
  98. package/dist/pairing.d.ts +22 -0
  99. package/dist/pairing.js +81 -0
  100. package/dist/personalization.d.ts +35 -0
  101. package/dist/personalization.js +73 -0
  102. package/dist/pglite-hnsw-bridge.d.ts +118 -0
  103. package/dist/pglite-hnsw-bridge.js +311 -0
  104. package/dist/pglite-store.d.ts +59 -0
  105. package/dist/pglite-store.js +180 -0
  106. package/dist/playbook.d.ts +79 -0
  107. package/dist/playbook.js +83 -0
  108. package/dist/playbooks/dental-intake.d.ts +20 -0
  109. package/dist/playbooks/dental-intake.js +112 -0
  110. package/dist/predictive-agent.d.ts +157 -0
  111. package/dist/predictive-agent.js +535 -0
  112. package/dist/prompt-optimizer.d.ts +18 -0
  113. package/dist/prompt-optimizer.js +104 -0
  114. package/dist/rate-limiter.d.ts +25 -0
  115. package/dist/rate-limiter.js +75 -0
  116. package/dist/safety-anneal.d.ts +83 -0
  117. package/dist/safety-anneal.js +153 -0
  118. package/dist/sandbox-controller.d.ts +12 -0
  119. package/dist/sandbox-controller.js +95 -0
  120. package/dist/satisfaction-metrics.d.ts +26 -0
  121. package/dist/satisfaction-metrics.js +61 -0
  122. package/dist/sensor-bridge.d.ts +53 -0
  123. package/dist/sensor-bridge.js +133 -0
  124. package/dist/session-repair.d.ts +27 -0
  125. package/dist/session-repair.js +66 -0
  126. package/dist/slack-finance-intake.d.ts +42 -0
  127. package/dist/slack-finance-intake.js +122 -0
  128. package/dist/symbolic-dynamics.d.ts +113 -0
  129. package/dist/symbolic-dynamics.js +420 -0
  130. package/dist/telemetry.d.ts +19 -0
  131. package/dist/telemetry.js +68 -0
  132. package/dist/text-embedding.d.ts +6 -0
  133. package/dist/text-embedding.js +42 -0
  134. package/dist/tier-classifier.d.ts +20 -0
  135. package/dist/tier-classifier.js +58 -0
  136. package/dist/tier-guard.d.ts +36 -0
  137. package/dist/tier-guard.js +56 -0
  138. package/dist/tui.d.ts +9 -0
  139. package/dist/tui.js +214 -0
  140. package/dist/update-security.d.ts +31 -0
  141. package/dist/update-security.js +112 -0
  142. package/dist/v-calibration.d.ts +16 -0
  143. package/dist/v-calibration.js +42 -0
  144. package/dist/value-calibration.d.ts +41 -0
  145. package/dist/value-calibration.js +133 -0
  146. package/dist/value-head.d.ts +20 -0
  147. package/dist/value-head.js +91 -0
  148. package/dist/wal-buffer.d.ts +23 -0
  149. package/dist/wal-buffer.js +144 -0
  150. package/dist/wiki-synthesizer.d.ts +80 -0
  151. package/dist/wiki-synthesizer.js +0 -0
  152. package/dist/worker-agent.d.ts +10 -0
  153. package/dist/worker-agent.js +19 -0
  154. package/package.json +65 -0
@@ -0,0 +1,133 @@
1
+ "use strict";
2
+ // ============================================================================
3
+ // 7-5. 가치 v 보정 — 일급 신뢰경계 (식(2)/계층2 소비 앞단)
4
+ // ----------------------------------------------------------------------------
5
+ // v 가 틀리면 계층2·3이 동시 오작동(단일 장애점)하므로, 소비 직전에 보정한다:
6
+ // ① 정규화(min-max) ② 이상치 윈저라이즈 ③ 적대적 팽창 탐지(오라클 실제결과와의 괴리)
7
+ // ④ 감사 로그 + 예산 상한 + 킬스위치
8
+ // 보정 통과한 v 만 계층2·3이 소비한다.
9
+ // ============================================================================
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.BudgetGuard = exports.ValueCalibrator = void 0;
12
+ exports.winsorize = winsorize;
13
+ exports.normalize = normalize;
14
+ function mean(xs) {
15
+ if (xs.length === 0)
16
+ return 0;
17
+ return xs.reduce((a, b) => a + b, 0) / xs.length;
18
+ }
19
+ /** 배열을 [pLow, pHigh] 분위수로 윈저라이즈(이상치 클리핑). */
20
+ function winsorize(values, pLow = 0.01, pHigh = 0.99) {
21
+ if (values.length === 0)
22
+ return [];
23
+ const sorted = [...values].sort((a, b) => a - b);
24
+ const q = (p) => sorted[Math.min(sorted.length - 1, Math.max(0, Math.floor(p * (sorted.length - 1))))];
25
+ const lo = q(pLow);
26
+ const hi = q(pHigh);
27
+ return values.map((v) => Math.min(hi, Math.max(lo, v)));
28
+ }
29
+ /** 루트 자식 Q들을 min-max 정규화 → v_norm∈[0,1]. */
30
+ function normalize(q, qMin, qMax) {
31
+ if (qMax - qMin < 1e-9)
32
+ return 0.5;
33
+ return Math.max(0, Math.min(1, (q - qMin) / (qMax - qMin)));
34
+ }
35
+ class ValueCalibrator {
36
+ minObservations;
37
+ history = new Map();
38
+ auditLog = [];
39
+ killed = false;
40
+ constructor(minObservations = 3) {
41
+ this.minObservations = minObservations;
42
+ }
43
+ /** 적대적 팽창 관측 기록: 소스가 주장한 v 와 오라클이 매긴 실제 결과를 비교용으로 저장. */
44
+ observe(source, claimedV, actualOutcome) {
45
+ let h = this.history.get(source);
46
+ if (!h) {
47
+ h = { claimed: [], actual: [] };
48
+ this.history.set(source, h);
49
+ }
50
+ h.claimed.push(Math.max(0, Math.min(1, claimedV)));
51
+ h.actual.push(Math.max(0, Math.min(1, actualOutcome)));
52
+ }
53
+ /** 소스의 과거 과대평가 정도 → 감쇠 계수∈[0.1,1]. 부풀릴수록 1에서 멀어진다. */
54
+ inflationPenalty(source) {
55
+ const h = this.history.get(source);
56
+ if (!h || h.claimed.length < this.minObservations)
57
+ return 1.0;
58
+ const mc = mean(h.claimed);
59
+ const ma = mean(h.actual);
60
+ if (mc <= ma + 0.05)
61
+ return 1.0; // 정직(또는 과소평가) → 감쇠 없음
62
+ const gap = Math.min(1, mc - ma);
63
+ return Math.max(0.1, 1 - gap);
64
+ }
65
+ /**
66
+ * 소비 직전 보정: 정규화된 v_norm 에 팽창 감쇠를 적용하고 감사 로그에 남긴다.
67
+ * 킬스위치가 내려가 있으면 0(자원 차단)을 반환한다.
68
+ */
69
+ calibrate(source, vNorm) {
70
+ if (this.killed) {
71
+ this.auditLog.push({ source, raw: vNorm, calibrated: 0, penalty: 0, t: Date.now() });
72
+ return 0;
73
+ }
74
+ const v = Math.max(0, Math.min(1, vNorm));
75
+ const penalty = this.inflationPenalty(source);
76
+ const calibrated = Math.max(0, Math.min(1, v * penalty));
77
+ this.auditLog.push({ source, raw: vNorm, calibrated, penalty, t: Date.now() });
78
+ return calibrated;
79
+ }
80
+ /** v 와 오라클 실제 결과의 상관(영가설 판정용). |corr| 낮으면 v 스케줄링 근거 약함. */
81
+ correlationWithOracle(source) {
82
+ const h = this.history.get(source);
83
+ if (!h || h.claimed.length < 2)
84
+ return 0;
85
+ const mc = mean(h.claimed);
86
+ const ma = mean(h.actual);
87
+ let num = 0;
88
+ let dc = 0;
89
+ let da = 0;
90
+ for (let i = 0; i < h.claimed.length; i++) {
91
+ const x = h.claimed[i] - mc;
92
+ const y = h.actual[i] - ma;
93
+ num += x * y;
94
+ dc += x * x;
95
+ da += y * y;
96
+ }
97
+ if (dc === 0 || da === 0)
98
+ return 0;
99
+ return num / Math.sqrt(dc * da);
100
+ }
101
+ getAuditLog() {
102
+ return this.auditLog;
103
+ }
104
+ // ---- S3 경계 보장 킬스위치 ----
105
+ kill() {
106
+ this.killed = true;
107
+ }
108
+ reset() {
109
+ this.killed = false;
110
+ }
111
+ isKilled() {
112
+ return this.killed;
113
+ }
114
+ }
115
+ exports.ValueCalibrator = ValueCalibrator;
116
+ /** 예산 상한 가드: 누적 토큰/비용이 상한을 넘으면 추가 소비를 차단. */
117
+ class BudgetGuard {
118
+ cap;
119
+ spent = 0;
120
+ constructor(cap) {
121
+ this.cap = cap;
122
+ }
123
+ trySpend(amount) {
124
+ if (this.spent + amount > this.cap)
125
+ return false;
126
+ this.spent += amount;
127
+ return true;
128
+ }
129
+ remaining() {
130
+ return Math.max(0, this.cap - this.spent);
131
+ }
132
+ }
133
+ exports.BudgetGuard = BudgetGuard;
@@ -0,0 +1,20 @@
1
+ /** 해시 n-gram 특징화: 후보 텍스트 + 목표 컨텍스트 → 고정차원 밀집 벡터(부호 해시). */
2
+ export declare function featurize(text: string, context: string, dim?: number): Float64Array;
3
+ /** 선형 로지스틱 회귀(경사하강 + L2). 오라클 라벨(pass=1/fail=0)로 학습. */
4
+ export declare class ValueHead {
5
+ private dim;
6
+ private w;
7
+ private b;
8
+ constructor(dim?: number);
9
+ /** X: 특징 벡터 배열, y: 0/1 라벨. */
10
+ fit(X: Float64Array[], y: number[], opts?: {
11
+ epochs?: number;
12
+ lr?: number;
13
+ l2?: number;
14
+ }): void;
15
+ predictProba(x: Float64Array): number;
16
+ }
17
+ /** 예상 오라클 호출 수(첫 통과까지) — 랭킹 품질 지표. 낮을수록 좋음. */
18
+ export declare function oracleCallsToFirstPass(ranked: {
19
+ pass: boolean;
20
+ }[]): number;
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+ // ============================================================================
3
+ // G4 착수 — 학습 가치 예측기(신경 잠재의 최소 실측 대리).
4
+ // ----------------------------------------------------------------------------
5
+ // 목적: g_fast 필터가 발동하지 않는 영역(δ=0, 또는 후보가 모두 타입-유효 = §4k 실 LLM 실측)에서
6
+ // 남은 유일한 지렛대는 "통과할 후보를 먼저 시도하도록 정렬"이다. 현재는 `gfastValue`(토큰겹침 휴리스틱).
7
+ // 여기서 **오라클 결과(pass/fail)로 학습**한 선형 로지스틱 회귀가 그 휴리스틱보다 나은 랭킹을 주는지 측정한다.
8
+ //
9
+ // 정직(제1계명): 이것은 **해시 특징 위의 선형 로지스틱**이다. 논문의 잠재 z_t·마스킹 브리지(비선형·학습 잠재)는
10
+ // **미구현(설계단계 🔶)**. 본 모듈은 "학습이 δ=0 랭킹을 개선하는가"의 최소 반증 가능한 측정 도구다.
11
+ // fit 은 실제 경사하강, predict 는 실제 시그모이드 — mock 없음. 이득은 held-out 측정으로만 주장한다.
12
+ // ============================================================================
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.ValueHead = void 0;
15
+ exports.featurize = featurize;
16
+ exports.oracleCallsToFirstPass = oracleCallsToFirstPass;
17
+ /** 해시 n-gram 특징화: 후보 텍스트 + 목표 컨텍스트 → 고정차원 밀집 벡터(부호 해시). */
18
+ function featurize(text, context, dim = 256) {
19
+ const v = new Float64Array(dim);
20
+ const toks = (s) => (s || '').toLowerCase().match(/[a-z0-9_]+/g) ?? [];
21
+ const hash = (s) => { let h = 2166136261 >>> 0; for (let i = 0; i < s.length; i++) {
22
+ h ^= s.charCodeAt(i);
23
+ h = Math.imul(h, 16777619) >>> 0;
24
+ } return h; };
25
+ const add = (tok, w) => { const h = hash(tok); v[h % dim] += ((h >>> 31) ? -1 : 1) * w; };
26
+ const ctx = new Set(toks(context));
27
+ const ct = toks(text);
28
+ for (let i = 0; i < ct.length; i++) {
29
+ add(ct[i], 1); // 단일 토큰
30
+ if (i + 1 < ct.length)
31
+ add(ct[i] + '_' + ct[i + 1], 1); // 바이그램
32
+ if (ctx.has(ct[i]))
33
+ add('__ctxhit', 1); // 컨텍스트 겹침 신호
34
+ }
35
+ add('__len', Math.min(ct.length / 50, 2)); // 길이(과대 후보 벌점 여지)
36
+ // L2 정규화(스케일 안정).
37
+ let n = 0;
38
+ for (let i = 0; i < dim; i++)
39
+ n += v[i] * v[i];
40
+ n = Math.sqrt(n) || 1;
41
+ for (let i = 0; i < dim; i++)
42
+ v[i] /= n;
43
+ return v;
44
+ }
45
+ const sigmoid = (z) => 1 / (1 + Math.exp(-z));
46
+ /** 선형 로지스틱 회귀(경사하강 + L2). 오라클 라벨(pass=1/fail=0)로 학습. */
47
+ class ValueHead {
48
+ dim;
49
+ w;
50
+ b = 0;
51
+ constructor(dim = 256) {
52
+ this.dim = dim;
53
+ this.w = new Float64Array(dim);
54
+ }
55
+ /** X: 특징 벡터 배열, y: 0/1 라벨. */
56
+ fit(X, y, opts = {}) {
57
+ const epochs = opts.epochs ?? 300, lr = opts.lr ?? 0.3, l2 = opts.l2 ?? 1e-3;
58
+ const n = X.length;
59
+ if (n === 0)
60
+ return;
61
+ for (let e = 0; e < epochs; e++) {
62
+ const gw = new Float64Array(this.dim);
63
+ let gb = 0;
64
+ for (let i = 0; i < n; i++) {
65
+ const p = this.predictProba(X[i]);
66
+ const err = p - y[i];
67
+ const xi = X[i];
68
+ for (let j = 0; j < this.dim; j++)
69
+ gw[j] += err * xi[j];
70
+ gb += err;
71
+ }
72
+ for (let j = 0; j < this.dim; j++)
73
+ this.w[j] -= lr * (gw[j] / n + l2 * this.w[j]);
74
+ this.b -= lr * (gb / n);
75
+ }
76
+ }
77
+ predictProba(x) {
78
+ let z = this.b;
79
+ for (let j = 0; j < this.dim; j++)
80
+ z += this.w[j] * x[j];
81
+ return sigmoid(z);
82
+ }
83
+ }
84
+ exports.ValueHead = ValueHead;
85
+ /** 예상 오라클 호출 수(첫 통과까지) — 랭킹 품질 지표. 낮을수록 좋음. */
86
+ function oracleCallsToFirstPass(ranked) {
87
+ for (let i = 0; i < ranked.length; i++)
88
+ if (ranked[i].pass)
89
+ return i + 1;
90
+ return ranked.length; // 통과 없음 = 전부 시도
91
+ }
@@ -0,0 +1,23 @@
1
+ export interface Message {
2
+ id?: number;
3
+ channel: string;
4
+ content: string;
5
+ timestamp: number;
6
+ }
7
+ export declare class SQLiteWalBuffer {
8
+ private db;
9
+ private dbPath;
10
+ constructor(dbPath: string);
11
+ init(): Promise<void>;
12
+ pushMessage(channel: string, content: string): Promise<void>;
13
+ popAllMessages(): Promise<Message[]>;
14
+ /**
15
+ * 7-6: ack 기반 at-least-once 읽기. 메시지를 삭제하지 않고 조회만 한다.
16
+ * 소비자가 처리 후 ackMessages(ids)로 명시 확인할 때까지 WAL에 남아 유실을 막는다.
17
+ */
18
+ peekMessages(): Promise<Message[]>;
19
+ /** 처리 완료된 메시지를 id로 확인(삭제). 멱등: 이미 없는 id는 무시된다. */
20
+ ackMessages(ids: number[]): Promise<void>;
21
+ getPendingCount(): Promise<number>;
22
+ close(): Promise<void>;
23
+ }
@@ -0,0 +1,144 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.SQLiteWalBuffer = void 0;
37
+ const sqlite3 = __importStar(require("sqlite3"));
38
+ class SQLiteWalBuffer {
39
+ db = null;
40
+ dbPath;
41
+ constructor(dbPath) {
42
+ this.dbPath = dbPath;
43
+ }
44
+ async init() {
45
+ return new Promise((resolve, reject) => {
46
+ this.db = new sqlite3.Database(this.dbPath, (err) => {
47
+ if (err)
48
+ return reject(err);
49
+ // Enable WAL (Write-Ahead Logging) mode
50
+ this.db.run('PRAGMA journal_mode=WAL;', (walErr) => {
51
+ if (walErr)
52
+ return reject(walErr);
53
+ this.db.run(`CREATE TABLE IF NOT EXISTS messages (
54
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
55
+ channel TEXT,
56
+ content TEXT,
57
+ timestamp INTEGER
58
+ )`, (tableErr) => {
59
+ if (tableErr)
60
+ return reject(tableErr);
61
+ resolve();
62
+ });
63
+ });
64
+ });
65
+ });
66
+ }
67
+ async pushMessage(channel, content) {
68
+ return new Promise((resolve, reject) => {
69
+ const timestamp = Date.now();
70
+ this.db.run('INSERT INTO messages (channel, content, timestamp) VALUES (?, ?, ?)', [channel, content, timestamp], (err) => {
71
+ if (err)
72
+ return reject(err);
73
+ resolve();
74
+ });
75
+ });
76
+ }
77
+ async popAllMessages() {
78
+ return new Promise((resolve, reject) => {
79
+ this.db.all('SELECT * FROM messages ORDER BY timestamp ASC', (err, rows) => {
80
+ if (err)
81
+ return reject(err);
82
+ const messages = rows.map(r => ({
83
+ id: r.id,
84
+ channel: r.channel,
85
+ content: r.content,
86
+ timestamp: r.timestamp
87
+ }));
88
+ // Delete all read messages to clear the queue
89
+ this.db.run('DELETE FROM messages', (delErr) => {
90
+ if (delErr)
91
+ return reject(delErr);
92
+ resolve(messages);
93
+ });
94
+ });
95
+ });
96
+ }
97
+ /**
98
+ * 7-6: ack 기반 at-least-once 읽기. 메시지를 삭제하지 않고 조회만 한다.
99
+ * 소비자가 처리 후 ackMessages(ids)로 명시 확인할 때까지 WAL에 남아 유실을 막는다.
100
+ */
101
+ async peekMessages() {
102
+ return new Promise((resolve, reject) => {
103
+ this.db.all('SELECT * FROM messages ORDER BY id ASC', (err, rows) => {
104
+ if (err)
105
+ return reject(err);
106
+ resolve(rows.map((r) => ({ id: r.id, channel: r.channel, content: r.content, timestamp: r.timestamp })));
107
+ });
108
+ });
109
+ }
110
+ /** 처리 완료된 메시지를 id로 확인(삭제). 멱등: 이미 없는 id는 무시된다. */
111
+ async ackMessages(ids) {
112
+ if (ids.length === 0)
113
+ return;
114
+ return new Promise((resolve, reject) => {
115
+ const placeholders = ids.map(() => '?').join(',');
116
+ this.db.run(`DELETE FROM messages WHERE id IN (${placeholders})`, ids, (err) => {
117
+ if (err)
118
+ return reject(err);
119
+ resolve();
120
+ });
121
+ });
122
+ }
123
+ async getPendingCount() {
124
+ return new Promise((resolve, reject) => {
125
+ this.db.get('SELECT COUNT(*) as count FROM messages', (err, row) => {
126
+ if (err)
127
+ return reject(err);
128
+ resolve(row ? row.count : 0);
129
+ });
130
+ });
131
+ }
132
+ async close() {
133
+ if (this.db) {
134
+ return new Promise((resolve, reject) => {
135
+ this.db.close((err) => {
136
+ if (err)
137
+ return reject(err);
138
+ resolve();
139
+ });
140
+ });
141
+ }
142
+ }
143
+ }
144
+ exports.SQLiteWalBuffer = SQLiteWalBuffer;
@@ -0,0 +1,80 @@
1
+ import { KnowledgeGraph, KnowledgeItem } from './knowledge-graph';
2
+ export interface WikiInput {
3
+ id: string;
4
+ content: string;
5
+ }
6
+ export type WikiSource = 'llm' | 'local-extractive';
7
+ export interface TokenMeasure {
8
+ /** 측정 방식: 제공자 실 usage 또는 오프라인 근사. */
9
+ method: 'provider-usage' | 'offline-approx';
10
+ rawChars: number;
11
+ wikiChars: number;
12
+ rawApproxTokens: number;
13
+ wikiApproxTokens: number;
14
+ /** 제공자 실 입력 토큰(LLM 합성 호출). 오프라인이면 null. */
15
+ providerInputTokens: number | null;
16
+ /** 문자 기준 절감률(원본 주입 대비). */
17
+ charSavedRatio: number;
18
+ /** 토큰 기준 절감률(근사 또는 제공자 기준). */
19
+ tokenSavedRatio: number;
20
+ }
21
+ export interface WikiResult {
22
+ clusterId: string;
23
+ wiki: string;
24
+ source: WikiSource;
25
+ provider: string | null;
26
+ /** 원본 항목들의 콘텐츠 해시(캐시 무효화 키). */
27
+ sourceHash: string;
28
+ tokens: TokenMeasure;
29
+ /** 정확성 프록시: 원본 핵심 토큰 중 WIKI 에 보존된 비율∈[0,1]. (오라클 과제성공과는 별개.) */
30
+ fidelity: number;
31
+ }
32
+ export interface SynthesizeOptions {
33
+ /** 강제로 로컬 추출만 사용(테스트·오프라인). 기본 false(키 있으면 LLM). */
34
+ forceLocal?: boolean;
35
+ /** 로컬 추출 시 최대 라인 수(기본 24). */
36
+ maxLines?: number;
37
+ /** 로컬 추출 시 최대 문자 수(기본 1200). */
38
+ maxChars?: number;
39
+ }
40
+ export declare function approxTokenCount(text: string): number;
41
+ export declare function contentHash(items: {
42
+ id: string;
43
+ content: string;
44
+ }[]): string;
45
+ /**
46
+ * 그래프에서 seed 노드의 1-hop 클러스터(참조·의존 이웃)를 모은다.
47
+ * similarity 엣지는 잡음이 많아 기본 제외(includeSimilarity 로 포함 가능).
48
+ */
49
+ export declare function clusterAround(graph: KnowledgeGraph, items: KnowledgeItem[], seedId: string, opts?: {
50
+ includeSimilarity?: boolean;
51
+ }): KnowledgeItem[];
52
+ /**
53
+ * 클러스터를 WIKI 로 합성한다. 키 있으면 LLM(`llm.ts` 재사용), 없거나 forceLocal 이면 로컬 추출.
54
+ * 토큰 절감과 충실도를 실측해 함께 반환한다.
55
+ */
56
+ export declare function synthesizeWiki(clusterId: string, cluster: WikiInput[], opts?: SynthesizeOptions): Promise<WikiResult>;
57
+ /**
58
+ * WIKI 캐시 — 원본 콘텐츠 해시로 무효화. 원본이 바뀌면(해시 변경) stale 로 판정해 재합성을 유도한다.
59
+ */
60
+ export declare class WikiCache {
61
+ private store;
62
+ private hits;
63
+ private misses;
64
+ /** 캐시 조회. 저장된 해시와 현재 sourceHash 가 일치할 때만 반환(아니면 stale → null). */
65
+ get(clusterId: string, sourceHash: string): WikiResult | null;
66
+ isStale(clusterId: string, sourceHash: string): boolean;
67
+ set(result: WikiResult): void;
68
+ stats(): {
69
+ size: number;
70
+ hits: number;
71
+ misses: number;
72
+ };
73
+ }
74
+ /**
75
+ * 캐시를 거친 합성: stale(원본 변경/미존재)일 때만 재합성하고, 아니면 캐시 재사용.
76
+ */
77
+ export declare function synthesizeWikiCached(cache: WikiCache, clusterId: string, cluster: WikiInput[], opts?: SynthesizeOptions): Promise<{
78
+ result: WikiResult;
79
+ recomputed: boolean;
80
+ }>;
Binary file
@@ -0,0 +1,10 @@
1
+ import { ISandbox } from './index';
2
+ export declare class WorkerAgent {
3
+ private sandbox;
4
+ constructor(sandbox: ISandbox);
5
+ executeTask(command: string): Promise<{
6
+ stdout: string;
7
+ stderr: string;
8
+ success: boolean;
9
+ }>;
10
+ }
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WorkerAgent = void 0;
4
+ class WorkerAgent {
5
+ sandbox;
6
+ constructor(sandbox) {
7
+ this.sandbox = sandbox;
8
+ }
9
+ // Stateless execution without MCTS
10
+ async executeTask(command) {
11
+ const result = await this.sandbox.runCommand(command);
12
+ return {
13
+ stdout: result.stdout,
14
+ stderr: result.stderr,
15
+ success: result.code === 0
16
+ };
17
+ }
18
+ }
19
+ exports.WorkerAgent = WorkerAgent;
package/package.json ADDED
@@ -0,0 +1,65 @@
1
+ {
2
+ "name": "@n2world/orchestrator",
3
+ "version": "1.1.0",
4
+ "description": "N2World 오케스트레이터 — 예측 실행 에이전트, A2A, 가치 스케줄러, PWA 대시보드",
5
+ "license": "MIT",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/suhopark1-tech/n2world.git",
11
+ "directory": "packages/orchestrator"
12
+ },
13
+ "homepage": "https://github.com/suhopark1-tech/n2world#readme",
14
+ "bugs": {
15
+ "url": "https://github.com/suhopark1-tech/n2world/issues"
16
+ },
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "engines": {
21
+ "node": ">=18"
22
+ },
23
+ "bin": {
24
+ "n2world": "./dist/cli.js"
25
+ },
26
+ "scripts": {
27
+ "build": "tsc && node -e \"require('fs').mkdirSync('dist/dashboard', {recursive:true}); ['index.html', 'chat.html', 'dental.html', 'manifest.json', 'service-worker.js', 'icon-192.png', 'freebie.png'].forEach(file => require('fs').copyFileSync('src/dashboard/' + file, 'dist/dashboard/' + file))\"",
28
+ "test": "jest",
29
+ "test:pglite": "node --experimental-vm-modules ../../node_modules/jest/bin/jest.js tests/phase_P1",
30
+ "bench:pglite": "node ../../benchmarks/pglite_p1.mjs && node ../../benchmarks/pglite_p1_5.mjs",
31
+ "bench:p2": "node ../../benchmarks/p2_relations.mjs",
32
+ "bench:p3": "node ../../benchmarks/p3_wiki.mjs",
33
+ "bench:p3.5": "node ../../benchmarks/p3_5_anneal.mjs",
34
+ "bench:p4": "node ../../benchmarks/p4_priors.mjs",
35
+ "bench:p4.7": "node ../../benchmarks/p4_7_commitgate.mjs",
36
+ "bench:p5": "node ../../benchmarks/p5_macaroon.mjs",
37
+ "bench:dod": "node ../../benchmarks/v2_dod.mjs",
38
+ "test:e2e-benchmark": "jest tests/phase6.test.ts -t \"E2E Coding Tasks\"",
39
+ "test:perf-benchmark": "jest tests/phase6.test.ts -t \"Performance Benchmarking\"",
40
+ "test:a2a-security": "jest tests/phase7.test.ts -t \"Macaroon A2A Secure Collaboration\"",
41
+ "test:overlay-compilation": "jest tests/phase7.test.ts -t \"OverlayFS Compilation Cache\"",
42
+ "test:ebpf-scheduler": "jest tests/phase7.test.ts -t \"eBPF cgroups v2 Scheduler Driver\"",
43
+ "test:advanced": "jest tests/advanced-features.test.ts"
44
+ },
45
+ "dependencies": {
46
+ "@ai-sdk/anthropic": "^2.0.0",
47
+ "@ai-sdk/google": "^3.0.82",
48
+ "@electric-sql/pglite": "^0.5.3",
49
+ "@n2world/core": "*",
50
+ "ai": "^6.0.204",
51
+ "chalk": "^4.1.2",
52
+ "dotenv": "^17.4.2",
53
+ "sqlite3": "^6.0.1",
54
+ "string-width": "^4.2.3",
55
+ "wrap-ansi": "^7.0.0",
56
+ "zod": "^4.4.3"
57
+ },
58
+ "devDependencies": {
59
+ "@types/jest": "^29.0.0",
60
+ "@types/node": "^20.0.0",
61
+ "jest": "^29.0.0",
62
+ "ts-jest": "^29.0.0",
63
+ "typescript": "^5.0.0"
64
+ }
65
+ }