@fiale-plus/pi-rogue-bundle 0.1.14 → 0.1.16

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.
@@ -0,0 +1,216 @@
1
+ import { createHash } from "node:crypto";
2
+ import { describe, expect, it } from "vitest";
3
+ import { createInMemoryContextBroker } from "./index.js";
4
+
5
+ describe("createInMemoryContextBroker", () => {
6
+ it("publishes stable, unique handles and looks up artifacts by handle", () => {
7
+ const broker = createInMemoryContextBroker();
8
+ const first = broker.publish({
9
+ sessionId: "session-a",
10
+ kind: "tool_output",
11
+ payload: "same payload",
12
+ summary: "tests passed",
13
+ tags: ["test"],
14
+ paths: ["packages/core"],
15
+ });
16
+ const second = broker.publish({
17
+ sessionId: "session-a",
18
+ kind: "tool_output",
19
+ payload: "same payload",
20
+ summary: "same payload repeat",
21
+ tags: ["test"],
22
+ paths: ["packages/core"],
23
+ });
24
+
25
+ expect(first.handle).not.toEqual(second.handle);
26
+ expect(first.handle).toMatch(/^ctx:\/\/session\/session-a\/tool_output\//);
27
+ expect(broker.lookup({ handle: first.handle })).toEqual([first]);
28
+ expect(broker.lookup({ handle: second.handle })).toEqual([second]);
29
+ });
30
+
31
+ it("filters by session, kind, tag, path, and text", () => {
32
+ const broker = createInMemoryContextBroker();
33
+ const core = broker.publish({
34
+ sessionId: "s1",
35
+ kind: "tool_output",
36
+ payload: "vitest packages/core passed",
37
+ tags: ["test", "core"],
38
+ paths: ["packages/core/src/context-broker.ts"],
39
+ });
40
+ broker.publish({
41
+ sessionId: "s2",
42
+ kind: "advisor_brief",
43
+ payload: "different payload",
44
+ tags: ["advisor"],
45
+ paths: ["packages/advisor/src/router.ts"],
46
+ });
47
+
48
+ expect(broker.lookup({ sessionId: "s1", kind: "tool_output", tag: "core" })).toEqual([core]);
49
+ expect(broker.lookup({ path: "packages/core" })).toEqual([core]);
50
+ expect(broker.lookup({ text: "vitest" })).toEqual([core]);
51
+ expect(broker.lookup({ sessionId: "s2", kind: "tool_output" })).toEqual([]);
52
+ });
53
+
54
+ it("uses a metadata-only summary when callers omit summaries", () => {
55
+ const broker = createInMemoryContextBroker({ briefBytes: 500 });
56
+ const artifact = broker.publish({
57
+ sessionId: "s",
58
+ kind: "tool_output",
59
+ payload: "SECRET_TOKEN=abc123\n".repeat(20),
60
+ paths: ["logs/secret-output.txt"],
61
+ });
62
+
63
+ const brief = broker.renderBrief({ sessionId: "s" });
64
+
65
+ expect(artifact.summary).toContain("payload stored externally");
66
+ expect(artifact.summary).not.toContain("SECRET_TOKEN");
67
+ expect(brief).not.toContain("SECRET_TOKEN");
68
+ expect(brief).toContain(artifact.handle);
69
+ });
70
+
71
+ it("enforces record caps by pruning oldest unpinned artifacts", () => {
72
+ const broker = createInMemoryContextBroker({ maxRecords: 2, defaultTtlMs: 0 });
73
+ const first = broker.publish({ sessionId: "s", kind: "memory_note", payload: "one", createdAt: 1 });
74
+ const second = broker.publish({ sessionId: "s", kind: "memory_note", payload: "two", createdAt: 2 });
75
+ const third = broker.publish({ sessionId: "s", kind: "memory_note", payload: "three", createdAt: 3 });
76
+
77
+ expect(broker.lookup({ id: first.id })).toEqual([]);
78
+ expect(broker.lookup({ id: second.id })).toEqual([second]);
79
+ expect(broker.lookup({ id: third.id })).toEqual([third]);
80
+ expect(broker.status().records).toBe(2);
81
+ });
82
+
83
+ it("applies caps independently per session", () => {
84
+ const broker = createInMemoryContextBroker({ maxRecords: 1, defaultTtlMs: 0 });
85
+ const sessionOne = broker.publish({ sessionId: "s1", kind: "tool_output", payload: "one", createdAt: 1 });
86
+ const sessionTwo = broker.publish({ sessionId: "s2", kind: "tool_output", payload: "two", createdAt: 2 });
87
+
88
+ expect(broker.lookup({ sessionId: "s1" })).toEqual([sessionOne]);
89
+ expect(broker.lookup({ sessionId: "s2" })).toEqual([sessionTwo]);
90
+ expect(broker.status().records).toBe(2);
91
+ });
92
+
93
+ it("uses sequence tie-breakers when createdAt timestamps tie", () => {
94
+ const broker = createInMemoryContextBroker({ maxRecords: 2, defaultTtlMs: 0 });
95
+ const first = broker.publish({ sessionId: "s", kind: "tool_output", payload: "alpha", createdAt: 1000 });
96
+ const second = broker.publish({ sessionId: "s", kind: "tool_output", payload: "bravo", createdAt: 1000 });
97
+ const third = broker.publish({ sessionId: "s", kind: "tool_output", payload: "charlie", createdAt: 1000 });
98
+
99
+ expect(broker.lookup({ id: first.id })).toEqual([]);
100
+ expect(broker.lookup({ id: second.id })).toEqual([second]);
101
+ expect(broker.lookup({ id: third.id })).toEqual([third]);
102
+ });
103
+
104
+ it("enforces byte caps by pruning oldest unpinned artifacts", () => {
105
+ const broker = createInMemoryContextBroker({ maxBytes: 6, defaultTtlMs: 0 });
106
+ const first = broker.publish({ sessionId: "s", kind: "tool_output", payload: "12345", createdAt: 1 });
107
+ const second = broker.publish({ sessionId: "s", kind: "tool_output", payload: "abcde", createdAt: 2 });
108
+
109
+ expect(broker.lookup({ id: first.id })).toEqual([]);
110
+ expect(broker.lookup({ id: second.id })).toEqual([second]);
111
+ expect(broker.status().bytes).toBe(5);
112
+ });
113
+
114
+ it("preserves the returned handle when a new artifact exceeds maxBytes", () => {
115
+ const broker = createInMemoryContextBroker({ maxBytes: 4, defaultTtlMs: 0 });
116
+ const artifact = broker.publish({ sessionId: "s", kind: "tool_output", payload: "oversized", createdAt: 1 });
117
+
118
+ expect(broker.lookup({ id: artifact.id })).toEqual([artifact]);
119
+ expect(broker.lookup({ handle: artifact.handle })).toEqual([artifact]);
120
+ expect(broker.status().bytes).toBe(Buffer.byteLength("oversized", "utf8"));
121
+ });
122
+
123
+ it("computes bytes and SHA-256 on raw Buffer payload bytes", () => {
124
+ const broker = createInMemoryContextBroker({ maxBytes: 1024, defaultTtlMs: 0 });
125
+ const payload = Buffer.from([0x66, 0xff, 0x61, 0x62, 0x80, 0x00]);
126
+ const artifact = broker.publish({ sessionId: "s", kind: "tool_output", payload, createdAt: 1 });
127
+ const expectedSha = createHash("sha256").update(payload).digest("hex");
128
+
129
+ expect(artifact.bytes).toBe(payload.length);
130
+ expect(artifact.sha256).toBe(expectedSha);
131
+ expect(Buffer.byteLength(artifact.payload, "utf8")).toBeGreaterThan(artifact.bytes);
132
+ });
133
+
134
+ it("keeps pinned artifacts visible while pruning unpinned records", () => {
135
+ const broker = createInMemoryContextBroker({ maxRecords: 2, defaultTtlMs: 0 });
136
+ const pinned = broker.publish({ sessionId: "s", kind: "diff", payload: "important", pinned: true, createdAt: 1 });
137
+ const older = broker.publish({ sessionId: "s", kind: "diff", payload: "temporary", createdAt: 2 });
138
+ const newer = broker.publish({ sessionId: "s", kind: "diff", payload: "latest", createdAt: 3 });
139
+
140
+ expect(broker.lookup({ id: pinned.id })).toEqual([pinned]);
141
+ expect(broker.lookup({ id: older.id })).toEqual([]);
142
+ expect(broker.lookup({ id: newer.id })).toEqual([newer]);
143
+ expect(broker.status().pinnedRecords).toBe(1);
144
+ });
145
+
146
+ it("expires unpinned artifacts by ttl", () => {
147
+ const broker = createInMemoryContextBroker({ defaultTtlMs: 10 });
148
+ const artifact = broker.publish({ sessionId: "s", kind: "tool_output", payload: "old", createdAt: 100 });
149
+
150
+ broker.prune(111);
151
+
152
+ expect(broker.lookup({ id: artifact.id })).toEqual([]);
153
+ });
154
+
155
+ it("prunes expired artifacts before lookup without an explicit prune call", () => {
156
+ const broker = createInMemoryContextBroker({ defaultTtlMs: 1 });
157
+ const artifact = broker.publish({ sessionId: "s", kind: "tool_output", payload: "expired", createdAt: 1 });
158
+
159
+ expect(broker.lookup({ id: artifact.id })).toEqual([]);
160
+ expect(broker.status().records).toBe(0);
161
+ });
162
+
163
+ it("omits expired artifacts from rendered prompt briefs", () => {
164
+ const broker = createInMemoryContextBroker({ defaultTtlMs: 1, briefBytes: 500 });
165
+ const artifact = broker.publish({ sessionId: "s", kind: "tool_output", payload: "expired secret", summary: "expired summary", createdAt: 1 });
166
+
167
+ const brief = broker.renderBrief({ sessionId: "s" });
168
+
169
+ expect(brief).not.toContain(artifact.handle);
170
+ expect(brief).not.toContain("expired summary");
171
+ });
172
+
173
+ it("keeps pinned expired artifacts visible until unpinned", () => {
174
+ const broker = createInMemoryContextBroker({ defaultTtlMs: 1 });
175
+ const artifact = broker.publish({ sessionId: "s", kind: "tool_output", payload: "pinned", pinned: true, createdAt: 1 });
176
+
177
+ expect(broker.lookup({ id: artifact.id })).toEqual([artifact]);
178
+ expect(broker.pin(artifact.id, false)).toBeNull();
179
+ expect(broker.lookup({ id: artifact.id })).toEqual([]);
180
+ });
181
+
182
+ it("renders a bounded prompt brief with lookup instructions", () => {
183
+ const broker = createInMemoryContextBroker({ briefBytes: 180 });
184
+ broker.publish({
185
+ sessionId: "s",
186
+ kind: "tool_output",
187
+ payload: "x".repeat(500),
188
+ summary: "large command output passed with no failures",
189
+ tags: ["test"],
190
+ paths: ["packages/core"],
191
+ });
192
+
193
+ const brief = broker.renderBrief();
194
+
195
+ expect(Buffer.byteLength(brief, "utf8")).toBeLessThanOrEqual(180);
196
+ expect(brief).toContain("Context Broker");
197
+ expect(brief).toContain("ctx://session/s/tool_output/");
198
+ });
199
+
200
+ it("enforces prompt brief budgets by UTF-8 byte length", () => {
201
+ const broker = createInMemoryContextBroker({ briefBytes: 170 });
202
+ broker.publish({
203
+ sessionId: "emoji-session",
204
+ kind: "tool_output",
205
+ payload: "✅".repeat(200),
206
+ summary: "✅ 測試 passed ".repeat(20),
207
+ tags: ["測試", "✅"],
208
+ paths: ["packages/核心/✅.ts"],
209
+ });
210
+
211
+ const brief = broker.renderBrief({ budgetBytes: 170 });
212
+
213
+ expect(Buffer.byteLength(brief, "utf8")).toBeLessThanOrEqual(170);
214
+ expect(brief).toContain("Context Broker");
215
+ });
216
+ });
@@ -0,0 +1,245 @@
1
+ import { createHash } from "node:crypto";
2
+ import { safeName } from "@fiale-plus/pi-core";
3
+ import type {
4
+ BoundedContextBroker,
5
+ ContextArtifact,
6
+ ContextArtifactInput,
7
+ ContextArtifactKind,
8
+ ContextBrokerOptions,
9
+ ContextBrokerStatus,
10
+ ContextLookupQuery,
11
+ } from "@fiale-plus/pi-core";
12
+
13
+ export type {
14
+ BoundedContextBroker,
15
+ ContextArtifact,
16
+ ContextArtifactInput,
17
+ ContextArtifactKind,
18
+ ContextBrokerOptions,
19
+ ContextBrokerStatus,
20
+ ContextLookupQuery,
21
+ } from "@fiale-plus/pi-core";
22
+
23
+ const DEFAULT_MAX_RECORDS = 256;
24
+ const DEFAULT_MAX_BYTES = 128 * 1024 * 1024;
25
+ const DEFAULT_TTL_MS = 7 * 24 * 60 * 60 * 1000;
26
+ const DEFAULT_SUMMARY_BYTES = 320;
27
+ const DEFAULT_BRIEF_BYTES = 2_000;
28
+
29
+ function normalizeList(values: string[] | undefined): string[] {
30
+ return [...new Set((values ?? []).map((value) => String(value || "").trim()).filter(Boolean))];
31
+ }
32
+
33
+ function payloadText(payload: string | Buffer): string {
34
+ return Buffer.isBuffer(payload) ? payload.toString("utf8") : String(payload ?? "");
35
+ }
36
+
37
+ function payloadBytes(payload: string | Buffer): number {
38
+ return Buffer.isBuffer(payload) ? payload.length : Buffer.byteLength(String(payload ?? ""), "utf8");
39
+ }
40
+
41
+ function hashPayload(payload: string | Buffer): string {
42
+ return createHash("sha256").update(Buffer.isBuffer(payload) ? payload : String(payload)).digest("hex");
43
+ }
44
+
45
+ function normalizeNeedle(value: string | undefined): string {
46
+ return String(value ?? "").trim().toLowerCase();
47
+ }
48
+
49
+ function truncateUtf8(text: string, maxBytes: number): string {
50
+ const limit = Math.max(0, Math.floor(maxBytes));
51
+ if (Buffer.byteLength(text, "utf8") <= limit) return text;
52
+ if (limit === 0) return "";
53
+
54
+ const ellipsis = "…";
55
+ const ellipsisBytes = Buffer.byteLength(ellipsis, "utf8");
56
+ const contentLimit = Math.max(0, limit - ellipsisBytes);
57
+ let used = 0;
58
+ let result = "";
59
+
60
+ for (const char of text) {
61
+ const bytes = Buffer.byteLength(char, "utf8");
62
+ if (used + bytes > contentLimit) break;
63
+ result += char;
64
+ used += bytes;
65
+ }
66
+
67
+ if (Buffer.byteLength(result + ellipsis, "utf8") <= limit) return result + ellipsis;
68
+ return result;
69
+ }
70
+
71
+ function summarizeArtifact(summary: string | undefined, kind: ContextArtifactKind, bytes: number, sha256: string, maxBytes: number): string {
72
+ const cleaned = String(summary ?? "").replace(/\s+/g, " ").trim();
73
+ if (cleaned) return truncateUtf8(cleaned, maxBytes);
74
+ return truncateUtf8(`[${kind} payload stored externally; ${bytes} bytes; sha256=${sha256.slice(0, 16)}]`, maxBytes);
75
+ }
76
+
77
+ function artifactMatches(artifact: ContextArtifact, query: ContextLookupQuery): boolean {
78
+ if (query.id && artifact.id !== query.id) return false;
79
+ if (query.handle && artifact.handle !== query.handle) return false;
80
+ if (query.sessionId && artifact.sessionId !== query.sessionId) return false;
81
+ if (query.kind && artifact.kind !== query.kind) return false;
82
+ if (query.branch && artifact.branch !== query.branch) return false;
83
+ if (query.tag && !artifact.tags.includes(query.tag)) return false;
84
+ if (query.path) {
85
+ const queryPath = query.path.replace(/\/$/, "");
86
+ if (!artifact.paths.some((path) => path === query.path || path.startsWith(`${queryPath}/`))) return false;
87
+ }
88
+ if (query.commandPrefix && !artifact.command?.startsWith(query.commandPrefix)) return false;
89
+
90
+ const text = normalizeNeedle(query.text);
91
+ if (text) {
92
+ const haystack = [artifact.summary, artifact.payload, artifact.command, artifact.tags.join(" "), artifact.paths.join(" ")]
93
+ .join("\n")
94
+ .toLowerCase();
95
+ if (!haystack.includes(text)) return false;
96
+ }
97
+
98
+ return true;
99
+ }
100
+
101
+ export function createInMemoryContextBroker(options: ContextBrokerOptions = {}): BoundedContextBroker {
102
+ const maxRecords = Math.max(1, Math.floor(options.maxRecords ?? DEFAULT_MAX_RECORDS));
103
+ const maxBytes = Math.max(1, Math.floor(options.maxBytes ?? DEFAULT_MAX_BYTES));
104
+ const defaultTtlMs = Math.max(0, Math.floor(options.defaultTtlMs ?? DEFAULT_TTL_MS));
105
+ const summaryBytes = Math.max(16, Math.floor(options.summaryBytes ?? DEFAULT_SUMMARY_BYTES));
106
+ const defaultBriefBytes = Math.max(64, Math.floor(options.briefBytes ?? DEFAULT_BRIEF_BYTES));
107
+ let artifacts: Array<ContextArtifact & { sequence: number }> = [];
108
+ let sequence = 0;
109
+
110
+ function currentStatus(): ContextBrokerStatus {
111
+ const bytes = artifacts.reduce((sum, artifact) => sum + artifact.bytes, 0);
112
+ const pinned = artifacts.filter((artifact) => artifact.pinned);
113
+ return {
114
+ records: artifacts.length,
115
+ bytes,
116
+ pinnedRecords: pinned.length,
117
+ pinnedBytes: pinned.reduce((sum, artifact) => sum + artifact.bytes, 0),
118
+ maxRecords,
119
+ maxBytes,
120
+ };
121
+ }
122
+
123
+ function dropExpired(now = Date.now(), protectedIds = new Set<string>()): void {
124
+ artifacts = artifacts.filter(
125
+ (artifact) => artifact.pinned || protectedIds.has(artifact.id) || !artifact.expiresAt || artifact.expiresAt > now,
126
+ );
127
+ }
128
+
129
+ function oldestRemovable(sessionId: string, protectedIds: Set<string>): { artifact: ContextArtifact & { sequence: number }; index: number } | undefined {
130
+ return artifacts
131
+ .map((artifact, index) => ({ artifact, index }))
132
+ .filter(({ artifact }) => artifact.sessionId === sessionId && !artifact.pinned && !protectedIds.has(artifact.id))
133
+ .sort((a, b) => {
134
+ if (a.artifact.createdAt !== b.artifact.createdAt) return a.artifact.createdAt - b.artifact.createdAt;
135
+ return a.artifact.sequence - b.artifact.sequence;
136
+ })[0];
137
+ }
138
+
139
+ function sessionWithinCaps(sessionId: string): boolean {
140
+ const sessionArtifacts = artifacts.filter((artifact) => artifact.sessionId === sessionId);
141
+ return sessionArtifacts.length <= maxRecords && sessionArtifacts.reduce((sum, artifact) => sum + artifact.bytes, 0) <= maxBytes;
142
+ }
143
+
144
+ function prune(now = Date.now(), protectedIds = new Set<string>()): ContextBrokerStatus {
145
+ dropExpired(now, protectedIds);
146
+
147
+ for (const sessionId of new Set(artifacts.map((artifact) => artifact.sessionId))) {
148
+ while (!sessionWithinCaps(sessionId)) {
149
+ const candidate = oldestRemovable(sessionId, protectedIds);
150
+ if (!candidate) break;
151
+ artifacts.splice(candidate.index, 1);
152
+ }
153
+ }
154
+
155
+ return currentStatus();
156
+ }
157
+
158
+ function status(): ContextBrokerStatus {
159
+ dropExpired();
160
+ return currentStatus();
161
+ }
162
+
163
+ function publish(input: ContextArtifactInput): ContextArtifact {
164
+ const now = input.createdAt ?? Date.now();
165
+ const payload = payloadText(input.payload);
166
+ const sha256 = hashPayload(input.payload);
167
+ const bytes = payloadBytes(input.payload);
168
+ const artifactSequence = ++sequence;
169
+ const id = `ctx-${now.toString(36)}-${String(artifactSequence).padStart(4, "0")}-${sha256.slice(0, 12)}`;
170
+ const session = safeName(input.sessionId || "session");
171
+ const kind = input.kind;
172
+ const handle = `ctx://session/${session}/${kind}/${sha256.slice(0, 16)}/${id}`;
173
+ const ttlMs = input.ttlMs ?? defaultTtlMs;
174
+
175
+ const artifact: ContextArtifact & { sequence: number } = {
176
+ id,
177
+ handle,
178
+ sessionId: input.sessionId,
179
+ kind,
180
+ createdAt: now,
181
+ updatedAt: now,
182
+ bytes,
183
+ sha256,
184
+ payload,
185
+ summary: summarizeArtifact(input.summary, kind, bytes, sha256, summaryBytes),
186
+ tags: normalizeList(input.tags),
187
+ paths: normalizeList(input.paths),
188
+ command: input.command?.trim() || undefined,
189
+ branch: input.branch?.trim() || undefined,
190
+ expiresAt: ttlMs > 0 ? now + ttlMs : undefined,
191
+ pinned: Boolean(input.pinned),
192
+ parentIds: normalizeList(input.parentIds),
193
+ sequence: artifactSequence,
194
+ };
195
+
196
+ artifacts = [artifact, ...artifacts];
197
+ prune(now, new Set([artifact.id]));
198
+ return artifact;
199
+ }
200
+
201
+ function lookup(query: ContextLookupQuery = {}): ContextArtifact[] {
202
+ dropExpired();
203
+ const limit = Math.max(1, Math.floor(query.limit ?? (artifacts.length || 1)));
204
+ return artifacts
205
+ .filter((artifact) => artifactMatches(artifact, query))
206
+ .sort((a, b) => Number(b.pinned) - Number(a.pinned) || b.createdAt - a.createdAt || b.sequence - a.sequence)
207
+ .slice(0, limit);
208
+ }
209
+
210
+ function pin(idOrHandle: string, pinned = true): ContextArtifact | null {
211
+ dropExpired();
212
+ const artifact = artifacts.find((candidate) => candidate.id === idOrHandle || candidate.handle === idOrHandle) ?? null;
213
+ if (!artifact) return null;
214
+ artifact.pinned = pinned;
215
+ artifact.updatedAt = Date.now();
216
+ prune();
217
+ return artifacts.find((candidate) => candidate.id === artifact.id) ?? null;
218
+ }
219
+
220
+ function renderBrief(query: ContextLookupQuery & { budgetBytes?: number } = {}): string {
221
+ const budget = Math.max(64, Math.floor(query.budgetBytes ?? defaultBriefBytes));
222
+ const lines = [
223
+ "## Context Broker",
224
+ `Budget: ${budget} bytes`,
225
+ ...lookup({ ...query, limit: query.limit ?? 8 }).map((artifact) => {
226
+ const pin = artifact.pinned ? " pinned" : "";
227
+ const path = artifact.paths.length ? ` paths=${artifact.paths.slice(0, 3).join(",")}` : "";
228
+ const tags = artifact.tags.length ? ` tags=${artifact.tags.slice(0, 3).join(",")}` : "";
229
+ return `- ${artifact.handle} kind=${artifact.kind}${pin}${path}${tags} summary="${artifact.summary}"`;
230
+ }),
231
+ "Lookup: use broker lookup by handle/path/tag/kind/session before replaying raw payloads.",
232
+ ];
233
+
234
+ return truncateUtf8(lines.join("\n"), budget);
235
+ }
236
+
237
+ return {
238
+ publish,
239
+ lookup,
240
+ pin,
241
+ prune,
242
+ status,
243
+ renderBrief,
244
+ };
245
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@fiale-plus/pi-rogue-bundle",
3
- "version": "0.1.14",
4
- "description": "Public Pi-Rogue bundle for advisor and orchestration. Single consolidated artefact (advisor and orchestration releases paused; their packages are private and bundled here).",
3
+ "version": "0.1.16",
4
+ "description": "Public Pi-Rogue bundle for advisor, orchestration, and beta context broker. Single consolidated artefact (leaf releases paused; private packages are bundled here).",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "repository": {
@@ -11,9 +11,13 @@
11
11
  "keywords": [
12
12
  "pi-package"
13
13
  ],
14
+ "scripts": {
15
+ "test": "cd ../.. && vitest run packages/bundle/src/*.test.ts"
16
+ },
14
17
  "main": "./src/index.ts",
15
18
  "exports": {
16
- ".": "./src/index.ts"
19
+ ".": "./src/index.ts",
20
+ "./context-broker": "./src/context-broker.ts"
17
21
  },
18
22
  "pi": {
19
23
  "extensions": [
@@ -28,11 +32,15 @@
28
32
  "@earendil-works/pi-coding-agent": "^0.74.0"
29
33
  },
30
34
  "dependencies": {
35
+ "@fiale-plus/pi-core": "^0.1.0",
31
36
  "@fiale-plus/pi-rogue-advisor": "^0.1.0",
37
+ "@fiale-plus/pi-rogue-context-broker": "^0.1.0",
32
38
  "@fiale-plus/pi-rogue-orchestration": "^0.1.0"
33
39
  },
34
40
  "bundledDependencies": [
41
+ "@fiale-plus/pi-core",
35
42
  "@fiale-plus/pi-rogue-advisor",
43
+ "@fiale-plus/pi-rogue-context-broker",
36
44
  "@fiale-plus/pi-rogue-orchestration"
37
45
  ],
38
46
  "publishConfig": {
@@ -0,0 +1 @@
1
+ export * from "@fiale-plus/pi-rogue-context-broker";
@@ -0,0 +1,63 @@
1
+ import { createInMemoryContextBroker } from "./context-broker.js";
2
+ import { afterEach, describe, expect, it } from "vitest";
3
+ import { registerBundle } from "./extension.js";
4
+
5
+ function createPiMock() {
6
+ const handlers = new Map<string, any[]>();
7
+ const commands = new Map<string, any>();
8
+ const pi: any = new Proxy({
9
+ on(name: string, handler: any) {
10
+ handlers.set(name, [...(handlers.get(name) ?? []), handler]);
11
+ },
12
+ registerCommand(name: string, options: any) {
13
+ commands.set(name, options);
14
+ },
15
+ getFlag() {
16
+ return undefined;
17
+ },
18
+ }, {
19
+ get(target, prop) {
20
+ if (prop in target) return (target as any)[prop];
21
+ if (typeof prop === "string" && prop.startsWith("__")) return undefined;
22
+ return () => undefined;
23
+ },
24
+ });
25
+ return { pi, handlers, commands };
26
+ }
27
+
28
+ describe("bundle extension defaults", () => {
29
+ const oldEnv = process.env.PI_CONTEXT_BROKER_ENABLED;
30
+
31
+ afterEach(() => {
32
+ if (oldEnv === undefined) delete process.env.PI_CONTEXT_BROKER_ENABLED;
33
+ else process.env.PI_CONTEXT_BROKER_ENABLED = oldEnv;
34
+ });
35
+
36
+ it("does not register the beta context broker by default", async () => {
37
+ delete process.env.PI_CONTEXT_BROKER_ENABLED;
38
+ const { pi, commands } = createPiMock();
39
+
40
+ await registerBundle(pi);
41
+
42
+ expect(commands.has("context")).toBe(false);
43
+ });
44
+
45
+ it("registers the beta context broker only when explicitly enabled", async () => {
46
+ process.env.PI_CONTEXT_BROKER_ENABLED = "true";
47
+ const { pi, commands } = createPiMock();
48
+
49
+ await registerBundle(pi);
50
+
51
+ expect(commands.has("context")).toBe(true);
52
+ });
53
+ });
54
+
55
+ describe("bundle context-broker export", () => {
56
+ it("exposes the beta context broker runtime for explicit opt-in", () => {
57
+ const broker = createInMemoryContextBroker({ defaultTtlMs: 0 });
58
+ const artifact = broker.publish({ sessionId: "bundle-test", kind: "memory_note", payload: "hello" });
59
+
60
+ expect(artifact.handle).toContain("ctx://session/bundle-test/memory_note/");
61
+ expect(broker.lookup({ handle: artifact.handle })).toEqual([artifact]);
62
+ });
63
+ });
package/src/extension.ts CHANGED
@@ -2,15 +2,26 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
2
  import { registerAdvisor } from "@fiale-plus/pi-rogue-advisor";
3
3
  import { registerOrchestration } from "@fiale-plus/pi-rogue-orchestration";
4
4
 
5
- export function registerBundle(pi: ExtensionAPI): void {
5
+ const ENABLED_VALUES = new Set(["1", "true", "yes", "on"]);
6
+
7
+ function contextBrokerBetaEnabled(): boolean {
8
+ return ENABLED_VALUES.has(String(process.env.PI_CONTEXT_BROKER_ENABLED ?? "").trim().toLowerCase());
9
+ }
10
+
11
+ export async function registerBundle(pi: ExtensionAPI): Promise<void> {
6
12
  const p = pi as any;
7
13
  if (p.__piRogueBundleRegistered) return;
8
14
  p.__piRogueBundleRegistered = true;
9
15
 
10
16
  registerAdvisor(pi);
11
17
  registerOrchestration(pi);
18
+
19
+ if (contextBrokerBetaEnabled()) {
20
+ const { registerContextBrokerBeta } = await import("@fiale-plus/pi-rogue-context-broker/extension");
21
+ registerContextBrokerBeta(pi);
22
+ }
12
23
  }
13
24
 
14
- export default function bundleExtension(pi: ExtensionAPI): void {
15
- registerBundle(pi);
25
+ export default function bundleExtension(pi: ExtensionAPI): Promise<void> {
26
+ return registerBundle(pi);
16
27
  }