@pi-chamber/web 0.3.3 → 0.5.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.
- package/README.md +1 -0
- package/bin/lib/cli-startup.js +1 -0
- package/dist/assets/CommitSection-Cz-ACBaD.js +1 -0
- package/dist/assets/DiagramEditor-BNUOrd9m.js +1 -0
- package/dist/assets/DiagramView-D4YR9YRt.js +1 -0
- package/dist/assets/{DiffView-DGD9DMS7.js → DiffView-DPW8dcg_.js} +3 -3
- package/dist/assets/FilesView-BFGIdY6b.js +14 -0
- package/dist/assets/GitView-CKtiKOfJ.js +6 -0
- package/dist/assets/JsonTreeView-c-UJUw3D.js +1 -0
- package/dist/assets/{MarkdownRendererImpl-V1HMFCjr.js → MarkdownRendererImpl-CvC9eXoa.js} +2 -2
- package/dist/assets/PatchDiff-YGHsZUIR.js +1 -0
- package/dist/assets/PierreDiffViewer-CoXa-JJK.js +136 -0
- package/dist/assets/SessionSwitcherContent-B7eep3dO.js +1 -0
- package/dist/assets/SessionSwitcherDropdown-CZOFeJHH.js +2 -0
- package/dist/assets/SessionUnreadDot-ClpeYFPz.js +1 -0
- package/dist/assets/SettingsView-CPmHHDbQ.js +4 -0
- package/dist/assets/SettingsWindow-2CBpoJ8H.js +1 -0
- package/dist/assets/{ToolOutputDialog-2zKUdGYL.js → ToolOutputDialog-HMW-Kh19.js} +6 -6
- package/dist/assets/ToolPartDiffPreview-C3nbNbxk.js +8 -0
- package/dist/assets/{VirtualizedFileDiff-UMgLcO4Q.js → VirtualizedFileDiff-DEX83nQ0.js} +3 -3
- package/dist/assets/{SessionSwitcherDropdown-o1RjhCfF.js → WindowsWindowControls-PPk5H89-.js} +172 -118
- package/dist/assets/collapsible-Dux-9hAC.js +1 -0
- package/dist/assets/computeVirtualFileMetrics-Cy0nxMJB.js +3 -0
- package/dist/assets/contextFileOpenGuard-Dn_38hd9.js +1 -0
- package/dist/assets/index--zDkVFU6.css +1 -0
- package/dist/assets/index-DU2OBBy5.js +8 -0
- package/dist/assets/index-EN7MioVf.js +1 -0
- package/dist/assets/isDiffPlainText-DSWRVq-W.js +1 -0
- package/dist/assets/isFilePlainText-7RAjjrQ5.js +1 -0
- package/dist/assets/{main-CmkRaMOR.js → main-BGKjg-qW.js} +8 -8
- package/dist/assets/main-DGHrBx_u.js +2 -0
- package/dist/assets/markdownCore-BYPqQtbE.js +3 -0
- package/dist/assets/miniChat-DW2PVX49.js +2 -0
- package/dist/assets/mobile-0Gxc02iO.js +2 -0
- package/dist/assets/renderElectronMiniChatApp-C-qpqp1i.js +2 -0
- package/dist/assets/renderMobileApp-UB9bhC1x.js +14 -0
- package/dist/assets/{runtimeSurface-CkHYYg0E.js → runtimeSurface-DefD-2Iv.js} +1 -1
- package/dist/assets/{useInlineCommentController-DD31jQNC.js → useInlineCommentController-B8p2XwXA.js} +2 -2
- package/dist/assets/usePanelSlide-CbqVf-y8.js +56 -0
- package/dist/assets/usePushVisibilityBeacon-CvjN-47R.js +10 -0
- package/dist/assets/useSwitcherItems-B6_F-J-z.js +1 -0
- package/dist/assets/{vendor-codemirror-language-data-Dp_Z-0GD.js → vendor-codemirror-language-data-BhBdEPsJ.js} +2 -2
- package/dist/assets/{vendor-katex-CHD9BdDO.js → vendor-katex-CNckGUMB.js} +1 -1
- package/dist/assets/{vendor-marked-i_gIkIP3.js → vendor-marked-CX41MkDF.js} +1 -1
- package/dist/assets/{web-components-Cct1r-wn.js → web-components-C9yVPsWN.js} +2 -2
- package/dist/index.html +8 -5
- package/dist/mini-chat.html +7 -4
- package/dist/mobile.html +7 -4
- package/dist/sw.js +1 -1
- package/package.json +1 -1
- package/server/index.js +27 -5
- package/server/lib/fs/routes.js +0 -21
- package/server/lib/git/DOCUMENTATION.md +15 -5
- package/server/lib/git/issue-2746-longpaths.test.js +11 -11
- package/server/lib/git/routes.js +80 -4
- package/server/lib/git/routes.test.js +135 -0
- package/server/lib/git/service.js +144 -82
- package/server/lib/git/service.test.js +182 -36
- package/server/lib/pi/extension-protocol.js +62 -0
- package/server/lib/pi/extension-protocol.test.js +34 -0
- package/server/lib/pi/fixtures/pichamber-gui-demo.ts +251 -0
- package/server/lib/pi/routes-extension-events.test.js +152 -0
- package/server/lib/pi/routes.js +345 -7
- package/server/lib/pi/routes.test.js +43 -28
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +8 -5
- package/server/lib/pi/session-daemon/extension-bridge.js +488 -0
- package/server/lib/pi/session-daemon/message-entry-aliases.js +53 -13
- package/server/lib/pi/session-daemon/message-entry-aliases.test.js +110 -0
- package/server/lib/pi/session-daemon/session-daemon-extensions.e2e.test.js +215 -0
- package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +559 -0
- package/server/lib/pi/session-daemon/session-daemon.js +483 -54
- package/server/lib/pi/session-daemon/session-daemon.test.js +212 -4
- package/server/lib/pi/session-daemon/session-retry-limits.js +55 -0
- package/server/lib/pi/session-daemon/session-retry-limits.test.js +53 -0
- package/server/lib/pi/session-daemon/skill-read-classifier.js +39 -0
- package/server/lib/pi/session-daemon/skill-read-classifier.test.js +41 -0
- package/server/lib/pi/session-daemon/supervisor.js +3 -0
- package/server/lib/pi/small-model-generation.js +104 -0
- package/server/lib/pi/small-model-generation.test.js +66 -0
- package/server/lib/preview/proxy-runtime.js +11 -1
- package/server/lib/preview/proxy-runtime.test.js +3 -0
- package/server/lib/relay/tunnel-host.js +1 -0
- package/server/lib/server/cors.js +0 -2
- package/server/lib/server/cors.test.js +4 -4
- package/server/lib/stt/DOCUMENTATION.md +38 -0
- package/server/lib/stt/audio.js +47 -0
- package/server/lib/stt/config-store.js +81 -0
- package/server/lib/stt/config-store.test.js +36 -0
- package/server/lib/stt/local/model-catalog.js +57 -0
- package/server/lib/stt/local/model-downloader.js +127 -0
- package/server/lib/stt/local/recognizer.js +64 -0
- package/server/lib/stt/local/sherpa-loader.js +43 -0
- package/server/lib/stt/local/worker-client.js +115 -0
- package/server/lib/stt/local/worker-process.js +64 -0
- package/server/lib/stt/protocol.js +38 -0
- package/server/lib/stt/protocol.test.js +17 -0
- package/server/lib/stt/providers/local-worker-provider.js +11 -0
- package/server/lib/stt/providers/openai-compatible-provider.js +31 -0
- package/server/lib/stt/providers/openai-compatible-provider.test.js +31 -0
- package/server/lib/stt/runtime.js +111 -0
- package/server/lib/stt/service.js +106 -0
- package/server/lib/stt/stream-manager.js +188 -0
- package/server/lib/stt/stream-manager.test.js +64 -0
- package/server/lib/ui-auth/DOCUMENTATION.md +1 -1
- package/server/lib/ui-auth/ui-auth.js +8 -3
- package/server/lib/ui-auth/ui-auth.test.js +8 -0
- package/server/lib/workspace/host.js +19 -3
- package/dist/assets/CommitSection-BAYzLtBf.js +0 -1
- package/dist/assets/DiagramEditor-D1yc4joK.js +0 -1
- package/dist/assets/DiagramView-CAlJiG11.js +0 -1
- package/dist/assets/FilesView-DB5VI7EN.js +0 -14
- package/dist/assets/GitView-CFlPcSn9.js +0 -6
- package/dist/assets/JsonTreeView-CoX1ZscV.js +0 -1
- package/dist/assets/PatchDiff-D6Gs7K5B.js +0 -1
- package/dist/assets/PierreDiffViewer-COYd5Qr-.js +0 -136
- package/dist/assets/SettingsView-BYqvfMTS.js +0 -4
- package/dist/assets/SettingsWindow-CtNS0tQn.js +0 -1
- package/dist/assets/ToolPartDiffPreview-CBFC9min.js +0 -8
- package/dist/assets/collapsible-Kx4bmsQM.js +0 -1
- package/dist/assets/computeVirtualFileMetrics-DdOCbMyK.js +0 -3
- package/dist/assets/contextFileOpenGuard-BRldMp0d.js +0 -1
- package/dist/assets/index-BAqpUCjs.js +0 -8
- package/dist/assets/index-CuSNEV7s.js +0 -1
- package/dist/assets/index-riABQmQ_.css +0 -1
- package/dist/assets/isDiffPlainText-CGIf0q8p.js +0 -1
- package/dist/assets/isFilePlainText-D4hgTRxT.js +0 -1
- package/dist/assets/main-By_pvk90.js +0 -2
- package/dist/assets/markdownCore-CAVCyFnI.js +0 -2
- package/dist/assets/miniChat-_XK2gGZE.js +0 -2
- package/dist/assets/mobile-B4E4JqAf.js +0 -2
- package/dist/assets/renderElectronMiniChatApp-Ca4hZgIz.js +0 -1
- package/dist/assets/renderMobileApp-ClA5Cnmw.js +0 -14
- package/dist/assets/usePanelSlide-a4c67FIY.js +0 -56
- package/dist/assets/useWindowTitle-DoHrUC5r.js +0 -10
- package/server/lib/pi/legacy-ui-model-defaults.js +0 -57
- package/server/lib/pi/legacy-ui-model-defaults.test.js +0 -65
|
@@ -986,7 +986,18 @@ describe('Pi session daemon spike', () => {
|
|
|
986
986
|
],
|
|
987
987
|
}],
|
|
988
988
|
});
|
|
989
|
-
|
|
989
|
+
runtime.session.sessionManager.getTree = () => [{
|
|
990
|
+
entry: { id: 'fake-entry', parentId: undefined, timestamp: '2026-01-01T00:00:00.000Z' },
|
|
991
|
+
label: 'checkpoint',
|
|
992
|
+
labelTimestamp: '2026-01-01T00:00:04.000Z',
|
|
993
|
+
children: [],
|
|
994
|
+
}];
|
|
995
|
+
await expect(client.request('sessions.tree', { sessionId: 'pi-session-persisted' })).resolves.toMatchObject({
|
|
996
|
+
result: {
|
|
997
|
+
rootId: 'pi-session-persisted',
|
|
998
|
+
nodes: [{ entryId: 'fake-entry', label: 'checkpoint', labelTimestamp: '2026-01-01T00:00:04.000Z' }],
|
|
999
|
+
},
|
|
1000
|
+
});
|
|
990
1001
|
await expect(client.request('sessions.navigate', { sessionId: 'pi-session-persisted', messageId: 'fake-entry' })).resolves.toMatchObject({ result: { session: { id: 'pi-session-persisted' } } });
|
|
991
1002
|
await expect(client.request('sessions.fork', { sessionId: 'pi-session-persisted', messageId: 'fake-entry' })).resolves.toMatchObject({ result: { session: { id: 'pi-session-forked' } } });
|
|
992
1003
|
await expect(client.request('sessions.clone', { sessionId: 'pi-session-forked' })).resolves.toMatchObject({ result: { session: { id: 'pi-session-forked' } } });
|
|
@@ -996,7 +1007,7 @@ describe('Pi session daemon spike', () => {
|
|
|
996
1007
|
const thinkingEvent = client.next((frame) => frame.event === 'session.thinking');
|
|
997
1008
|
await expect(client.request('sessions.setThinking', { sessionId: 'pi-session-forked', thinking: 'minimal' })).resolves.toMatchObject({ result: {} });
|
|
998
1009
|
await expect(thinkingEvent).resolves.toMatchObject({ payload: { thinking: 'minimal' } });
|
|
999
|
-
await expect(client.request('sessions.compact', { sessionId: 'pi-session-forked', thinking: 'medium' })).resolves.toMatchObject({ result: {} });
|
|
1010
|
+
await expect(client.request('sessions.compact', { sessionId: 'pi-session-forked', thinking: 'medium' })).resolves.toMatchObject({ result: { accepted: true } });
|
|
1000
1011
|
expect(runtime.session.compacted).toBe(1);
|
|
1001
1012
|
await expect(client.request('sessions.prompt', { sessionId: 'pi-session-forked', text: 'prompt' })).resolves.toMatchObject({ result: { accepted: true, messageId: 'fake-entry' } });
|
|
1002
1013
|
expect(runtime.session.sent).toEqual([{ text: 'prompt', options: undefined }]);
|
|
@@ -1122,14 +1133,16 @@ describe('Pi session daemon spike', () => {
|
|
|
1122
1133
|
const agentDir = join(root, 'agent');
|
|
1123
1134
|
const endpoint = testDaemonEndpoint(root);
|
|
1124
1135
|
await Promise.all([mkdir(cwd), mkdir(agentDir)]);
|
|
1136
|
+
const skillPath = join(agentDir, 'skills', 'directory-name', 'SKILL.md');
|
|
1125
1137
|
const loader = {
|
|
1126
|
-
getSkills: () => ({ skills: [{ name: 'review', description: 'Review changes', filePath:
|
|
1138
|
+
getSkills: () => ({ skills: [{ name: 'review', description: 'Review changes', filePath: skillPath, sourceInfo: { scope: 'user', origin: 'top-level' } }] }),
|
|
1127
1139
|
getPrompts: () => ({ prompts: [] }),
|
|
1128
1140
|
getAgentsFiles: () => ({ agentsFiles: [] }),
|
|
1129
1141
|
};
|
|
1142
|
+
const session = new FakeSession();
|
|
1130
1143
|
daemon = createSessionDaemon({
|
|
1131
1144
|
endpoint, credential, cwd, agentDir,
|
|
1132
|
-
createRuntime: async () => ({ session
|
|
1145
|
+
createRuntime: async () => ({ cwd, session, services: { resourceLoader: loader }, async dispose() {} }),
|
|
1133
1146
|
});
|
|
1134
1147
|
await daemon.start();
|
|
1135
1148
|
const client = connectClient(endpoint);
|
|
@@ -1139,6 +1152,48 @@ describe('Pi session daemon spike', () => {
|
|
|
1139
1152
|
const globalAgents = listed.result.agents.find((resource) => resource.location === 'global');
|
|
1140
1153
|
expect(globalAgents).toMatchObject({ kind: 'agents', name: 'AGENTS.md', editable: true });
|
|
1141
1154
|
expect(JSON.stringify(listed.result)).not.toContain(agentDir);
|
|
1155
|
+
|
|
1156
|
+
const skillToolStart = client.next((frame) => frame.event === 'session.tool.start' && frame.payload?.toolCallId === 'skill-read');
|
|
1157
|
+
session.emit({ type: 'tool_execution_start', toolCallId: 'skill-read', toolName: 'read', args: { path: skillPath } });
|
|
1158
|
+
await expect(skillToolStart).resolves.toMatchObject({
|
|
1159
|
+
payload: { metadata: { pichamber: { skill: { name: 'review' } } } },
|
|
1160
|
+
});
|
|
1161
|
+
const skillToolEnd = client.next((frame) => frame.event === 'session.tool.end' && frame.payload?.toolCallId === 'skill-read');
|
|
1162
|
+
session.emit({
|
|
1163
|
+
type: 'tool_execution_end', toolCallId: 'skill-read', toolName: 'read',
|
|
1164
|
+
result: { content: [{ type: 'text', text: 'skill content' }], details: { truncation: { truncated: false } } },
|
|
1165
|
+
isError: false,
|
|
1166
|
+
});
|
|
1167
|
+
await expect(skillToolEnd).resolves.toMatchObject({
|
|
1168
|
+
payload: {
|
|
1169
|
+
metadata: {
|
|
1170
|
+
truncation: { truncated: false },
|
|
1171
|
+
pichamber: { skill: { name: 'review' } },
|
|
1172
|
+
},
|
|
1173
|
+
},
|
|
1174
|
+
});
|
|
1175
|
+
|
|
1176
|
+
session.entries = [{
|
|
1177
|
+
type: 'message',
|
|
1178
|
+
id: 'assistant-skill-read',
|
|
1179
|
+
timestamp: '2026-01-01T00:00:02.000Z',
|
|
1180
|
+
message: {
|
|
1181
|
+
role: 'assistant', provider: 'test', model: 'model',
|
|
1182
|
+
content: [{ type: 'toolCall', id: 'persisted-skill-read', name: 'read', arguments: { path: skillPath } }],
|
|
1183
|
+
},
|
|
1184
|
+
}, {
|
|
1185
|
+
type: 'message',
|
|
1186
|
+
id: 'skill-read-result',
|
|
1187
|
+
timestamp: '2026-01-01T00:00:03.000Z',
|
|
1188
|
+
message: {
|
|
1189
|
+
role: 'toolResult', toolCallId: 'persisted-skill-read', toolName: 'read',
|
|
1190
|
+
content: [{ type: 'text', text: 'skill content' }], isError: false,
|
|
1191
|
+
},
|
|
1192
|
+
}];
|
|
1193
|
+
await expect(client.request('sessions.open', { sessionId: session.sessionId, directory: cwd })).resolves.toMatchObject({
|
|
1194
|
+
result: { messages: [{ parts: [expect.objectContaining({ metadata: { pichamber: { skill: { name: 'review' } } } })] }] },
|
|
1195
|
+
});
|
|
1196
|
+
|
|
1142
1197
|
await expect(client.request('resources.update', { resourceId: globalAgents.id, content: '# Global instructions\n' })).resolves.toMatchObject({ result: { agents: expect.any(Array) } });
|
|
1143
1198
|
await expect(readFile(join(agentDir, 'AGENTS.md'), 'utf8')).resolves.toBe('# Global instructions\n');
|
|
1144
1199
|
await client.close();
|
|
@@ -1201,6 +1256,82 @@ describe('Pi session daemon spike', () => {
|
|
|
1201
1256
|
await client.close();
|
|
1202
1257
|
});
|
|
1203
1258
|
|
|
1259
|
+
it('acknowledges manual compaction before summarization completes and publishes its outcome', async () => {
|
|
1260
|
+
const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-compact-'));
|
|
1261
|
+
const endpoint = testDaemonEndpoint(root);
|
|
1262
|
+
const session = new FakeSession('pi-session-compact');
|
|
1263
|
+
let finishCompaction;
|
|
1264
|
+
session.compact = async (customInstructions) => {
|
|
1265
|
+
session.compacted += 1;
|
|
1266
|
+
session.compactionInstructions = customInstructions;
|
|
1267
|
+
session.emit({ type: 'compaction_start', reason: 'manual' });
|
|
1268
|
+
await new Promise((resolve) => { finishCompaction = resolve; });
|
|
1269
|
+
session.emit({
|
|
1270
|
+
type: 'compaction_end',
|
|
1271
|
+
reason: 'manual',
|
|
1272
|
+
result: { tokensBefore: 120_000, estimatedTokensAfter: 24_000 },
|
|
1273
|
+
aborted: false,
|
|
1274
|
+
willRetry: false,
|
|
1275
|
+
});
|
|
1276
|
+
};
|
|
1277
|
+
daemon = createSessionDaemon({ endpoint, credential, cwd: root, createRuntime: async () => ({ session, async dispose() {} }) });
|
|
1278
|
+
await daemon.start();
|
|
1279
|
+
const client = connectClient(endpoint);
|
|
1280
|
+
await client.authenticate();
|
|
1281
|
+
await client.request('sessions.create', { cwd: root });
|
|
1282
|
+
|
|
1283
|
+
const started = client.next((frame) => frame.event === 'session.compaction' && frame.payload.phase === 'running');
|
|
1284
|
+
const completed = client.next((frame) => frame.event === 'session.compaction' && frame.payload.phase === 'completed');
|
|
1285
|
+
await expect(client.request('sessions.compact', {
|
|
1286
|
+
sessionId: 'pi-session-compact',
|
|
1287
|
+
customInstructions: 'Keep the unresolved test failures',
|
|
1288
|
+
})).resolves.toMatchObject({ result: { accepted: true } });
|
|
1289
|
+
expect(session.compacted).toBe(1);
|
|
1290
|
+
expect(session.compactionInstructions).toBe('Keep the unresolved test failures');
|
|
1291
|
+
await expect(started).resolves.toMatchObject({ payload: { phase: 'running', reason: 'manual' } });
|
|
1292
|
+
|
|
1293
|
+
const observer = connectClient(endpoint);
|
|
1294
|
+
const snapshot = await observer.authenticate();
|
|
1295
|
+
expect(snapshot.payload.compaction).toMatchObject({ phase: 'running', reason: 'manual' });
|
|
1296
|
+
await observer.close();
|
|
1297
|
+
|
|
1298
|
+
const retrying = client.next((frame) => frame.event === 'session.compaction' && frame.payload.phase === 'retrying');
|
|
1299
|
+
session.emit({ type: 'summarization_retry_scheduled', attempt: 1, maxAttempts: 3, delayMs: 2_000, errorMessage: 'temporary provider failure' });
|
|
1300
|
+
await expect(retrying).resolves.toMatchObject({
|
|
1301
|
+
payload: { phase: 'retrying', attempt: 1, maxAttempts: 3, message: 'temporary provider failure' },
|
|
1302
|
+
});
|
|
1303
|
+
|
|
1304
|
+
finishCompaction();
|
|
1305
|
+
await expect(completed).resolves.toMatchObject({
|
|
1306
|
+
payload: {
|
|
1307
|
+
phase: 'completed',
|
|
1308
|
+
reason: 'manual',
|
|
1309
|
+
tokensBefore: 120_000,
|
|
1310
|
+
estimatedTokensAfter: 24_000,
|
|
1311
|
+
},
|
|
1312
|
+
});
|
|
1313
|
+
await client.close();
|
|
1314
|
+
});
|
|
1315
|
+
|
|
1316
|
+
it('publishes a terminal compaction failure when the SDK rejects without an end event', async () => {
|
|
1317
|
+
const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-compact-failure-'));
|
|
1318
|
+
const endpoint = testDaemonEndpoint(root);
|
|
1319
|
+
const session = new FakeSession('pi-session-compact-failure');
|
|
1320
|
+
session.compact = async () => { throw new Error('summary provider unavailable'); };
|
|
1321
|
+
daemon = createSessionDaemon({ endpoint, credential, cwd: root, createRuntime: async () => ({ session, async dispose() {} }) });
|
|
1322
|
+
await daemon.start();
|
|
1323
|
+
const client = connectClient(endpoint);
|
|
1324
|
+
await client.authenticate();
|
|
1325
|
+
await client.request('sessions.create', { cwd: root });
|
|
1326
|
+
|
|
1327
|
+
const failed = client.next((frame) => frame.event === 'session.compaction' && frame.payload.phase === 'failed');
|
|
1328
|
+
await expect(client.request('sessions.compact', { sessionId: session.sessionId })).resolves.toMatchObject({ result: { accepted: true } });
|
|
1329
|
+
await expect(failed).resolves.toMatchObject({
|
|
1330
|
+
payload: { phase: 'failed', reason: 'manual', message: 'summary provider unavailable', willRetry: false },
|
|
1331
|
+
});
|
|
1332
|
+
await client.close();
|
|
1333
|
+
});
|
|
1334
|
+
|
|
1204
1335
|
it('maps all core session event families to sequenced public-safe daemon frames', async () => {
|
|
1205
1336
|
const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-'));
|
|
1206
1337
|
const endpoint = testDaemonEndpoint(root);
|
|
@@ -1269,6 +1400,52 @@ describe('Pi session daemon spike', () => {
|
|
|
1269
1400
|
await client.close();
|
|
1270
1401
|
});
|
|
1271
1402
|
|
|
1403
|
+
it('publishes extension-authored session names through the catalog event', async () => {
|
|
1404
|
+
const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-session-name-'));
|
|
1405
|
+
const endpoint = testDaemonEndpoint(root);
|
|
1406
|
+
const session = new FakeSession('pi-session-name');
|
|
1407
|
+
daemon = createSessionDaemon({ endpoint, credential, cwd: root, createRuntime: async () => ({ session, async dispose() {} }) });
|
|
1408
|
+
await daemon.start();
|
|
1409
|
+
const client = connectClient(endpoint);
|
|
1410
|
+
await client.authenticate();
|
|
1411
|
+
await client.request('sessions.create', { cwd: root });
|
|
1412
|
+
|
|
1413
|
+
const updated = client.next((frame) => frame.event === 'session.updated');
|
|
1414
|
+
session.emit({ type: 'session_info_changed', name: 'Extension title' });
|
|
1415
|
+
await expect(updated).resolves.toMatchObject({
|
|
1416
|
+
payload: { sessionId: 'pi-session-name', directory: root, title: 'Extension title' },
|
|
1417
|
+
});
|
|
1418
|
+
await client.close();
|
|
1419
|
+
});
|
|
1420
|
+
|
|
1421
|
+
it('publishes model selections made through the Pi session event stream', async () => {
|
|
1422
|
+
const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-model-select-'));
|
|
1423
|
+
const endpoint = testDaemonEndpoint(root);
|
|
1424
|
+
const session = new FakeSession('pi-session-model-select');
|
|
1425
|
+
daemon = createSessionDaemon({ endpoint, credential, cwd: root, createRuntime: async () => ({ session, async dispose() {} }) });
|
|
1426
|
+
await daemon.start();
|
|
1427
|
+
const client = connectClient(endpoint);
|
|
1428
|
+
await client.authenticate();
|
|
1429
|
+
await client.request('sessions.create', { cwd: root });
|
|
1430
|
+
|
|
1431
|
+
const selected = client.next((frame) => frame.event === 'session.model');
|
|
1432
|
+
session.emit({
|
|
1433
|
+
type: 'model_select',
|
|
1434
|
+
model: { provider: 'moonshot', id: 'kimi-k2' },
|
|
1435
|
+
previousModel: { provider: 'openai', id: 'gpt-5' },
|
|
1436
|
+
source: 'extension',
|
|
1437
|
+
});
|
|
1438
|
+
|
|
1439
|
+
await expect(selected).resolves.toMatchObject({
|
|
1440
|
+
payload: {
|
|
1441
|
+
sessionId: 'pi-session-model-select',
|
|
1442
|
+
directory: root,
|
|
1443
|
+
model: { providerId: 'moonshot', modelId: 'kimi-k2' },
|
|
1444
|
+
},
|
|
1445
|
+
});
|
|
1446
|
+
await client.close();
|
|
1447
|
+
});
|
|
1448
|
+
|
|
1272
1449
|
it('keeps retry attempts attached to the original user turn until Pi settles', async () => {
|
|
1273
1450
|
const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-retry-'));
|
|
1274
1451
|
const endpoint = testDaemonEndpoint(root);
|
|
@@ -1530,6 +1707,37 @@ describe('Pi session daemon spike', () => {
|
|
|
1530
1707
|
await client.close();
|
|
1531
1708
|
});
|
|
1532
1709
|
|
|
1710
|
+
it('settles an extension command that completes without starting an agent turn', async () => {
|
|
1711
|
+
const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-command-settle-'));
|
|
1712
|
+
const endpoint = testDaemonEndpoint(root);
|
|
1713
|
+
const sessionFile = join(root, 'session-1.jsonl');
|
|
1714
|
+
await writeFile(sessionFile, `{"type":"session","id":"session-1","cwd":"${root}"}\n`);
|
|
1715
|
+
const session = new FakeSession('session-1', sessionFile);
|
|
1716
|
+
daemon = createSessionDaemon({
|
|
1717
|
+
endpoint,
|
|
1718
|
+
credential,
|
|
1719
|
+
cwd: root,
|
|
1720
|
+
createRuntime: async () => new FakeRuntime({ cwd: root, session }),
|
|
1721
|
+
listSessions: async () => [
|
|
1722
|
+
{ path: sessionFile, id: 'session-1', cwd: root, created: new Date(), modified: new Date(), messageCount: 0 },
|
|
1723
|
+
],
|
|
1724
|
+
});
|
|
1725
|
+
await daemon.start();
|
|
1726
|
+
const client = connectClient(endpoint);
|
|
1727
|
+
await client.authenticate();
|
|
1728
|
+
|
|
1729
|
+
const settled = client.next((frame) => frame.event === 'session.lifecycle' && frame.payload.state === 'idle');
|
|
1730
|
+
await expect(client.request('sessions.prompt', {
|
|
1731
|
+
sessionId: 'session-1',
|
|
1732
|
+
text: '/balance',
|
|
1733
|
+
})).resolves.toMatchObject({ result: { accepted: true } });
|
|
1734
|
+
|
|
1735
|
+
await expect(settled).resolves.toMatchObject({
|
|
1736
|
+
payload: { sessionId: 'session-1', directory: root, state: 'idle' },
|
|
1737
|
+
});
|
|
1738
|
+
await client.close();
|
|
1739
|
+
});
|
|
1740
|
+
|
|
1533
1741
|
it('acknowledges a prompt without waiting for the agent turn to finish', async () => {
|
|
1534
1742
|
const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-prompt-ack-'));
|
|
1535
1743
|
const endpoint = testDaemonEndpoint(root);
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
|
|
4
|
+
export const PI_FALLBACK_RETRY_LIMIT = 3;
|
|
5
|
+
const PI_MIN_RETRY_LIMIT = 0;
|
|
6
|
+
const PI_MAX_RETRY_LIMIT = 10;
|
|
7
|
+
|
|
8
|
+
const isValidRetryLimit = (value) => Number.isInteger(value) && value >= PI_MIN_RETRY_LIMIT && value <= PI_MAX_RETRY_LIMIT;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Resolve the retry limit a new session should run with.
|
|
12
|
+
*
|
|
13
|
+
* Precedence: an explicit per-create payload value wins; otherwise the
|
|
14
|
+
* PiChamber default-retry-limit sidecar setting applies. When neither is
|
|
15
|
+
* configured the result is `undefined` and the caller must leave the runtime's
|
|
16
|
+
* own retry settings untouched — Pi stays authoritative and its built-in
|
|
17
|
+
* default (3) already matches the documented fallback.
|
|
18
|
+
*/
|
|
19
|
+
const resolveEffectiveRetryLimit = async ({ payloadRetryLimit, readSettingsFile = readFile, settingsPath } = {}) => {
|
|
20
|
+
if (payloadRetryLimit !== undefined) {
|
|
21
|
+
if (!isValidRetryLimit(payloadRetryLimit)) {
|
|
22
|
+
throw new Error('The retry limit must be an integer between 0 and 10.');
|
|
23
|
+
}
|
|
24
|
+
return payloadRetryLimit;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
if (settingsPath !== undefined) {
|
|
28
|
+
try {
|
|
29
|
+
const raw = await readSettingsFile(settingsPath, 'utf8');
|
|
30
|
+
const parsed = JSON.parse(raw);
|
|
31
|
+
if (isValidRetryLimit(parsed?.defaultRetryLimit)) return parsed.defaultRetryLimit;
|
|
32
|
+
if (parsed?.defaultRetryLimit !== undefined && parsed?.defaultRetryLimit !== null) {
|
|
33
|
+
throw new Error('The retry limit must be an integer between 0 and 10.');
|
|
34
|
+
}
|
|
35
|
+
} catch (error) {
|
|
36
|
+
// A malformed sidecar value must fail loudly; absence (ENOENT / empty
|
|
37
|
+
// file) is the normal no-override case and resolves to undefined.
|
|
38
|
+
if (error?.code === 'ENOENT') return undefined;
|
|
39
|
+
if (error instanceof SyntaxError || error?.message?.includes('retry limit')) throw error;
|
|
40
|
+
throw error;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return undefined;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
/** Convenience wrapper used by the daemon with its standard data-dir path. */
|
|
47
|
+
export const resolveEffectiveRetryLimitFromDataDir = async ({ payloadRetryLimit, dataDir }) => (
|
|
48
|
+
resolveEffectiveRetryLimit({
|
|
49
|
+
payloadRetryLimit,
|
|
50
|
+
// An explicit payload value never reads the sidecar, so no path is needed.
|
|
51
|
+
...(payloadRetryLimit === undefined && dataDir !== undefined
|
|
52
|
+
? { settingsPath: join(dataDir, 'pi', 'settings.json') }
|
|
53
|
+
: {}),
|
|
54
|
+
})
|
|
55
|
+
);
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { describe, expect, test } from 'vitest';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { mkdtempSync, writeFileSync, mkdirSync } from 'node:fs';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import {
|
|
6
|
+
PI_FALLBACK_RETRY_LIMIT,
|
|
7
|
+
resolveEffectiveRetryLimitFromDataDir as resolveEffectiveRetryLimit,
|
|
8
|
+
} from './session-retry-limits.js';
|
|
9
|
+
|
|
10
|
+
const makeDataDir = (sidecar) => {
|
|
11
|
+
const dataDir = mkdtempSync(join(tmpdir(), 'pichamber-retry-'));
|
|
12
|
+
if (sidecar !== undefined) {
|
|
13
|
+
mkdirSync(join(dataDir, 'pi'), { recursive: true });
|
|
14
|
+
writeFileSync(join(dataDir, 'pi', 'settings.json'), JSON.stringify(sidecar));
|
|
15
|
+
}
|
|
16
|
+
return dataDir;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
describe('resolveEffectiveRetryLimit', () => {
|
|
20
|
+
test('explicit payload value wins and is validated', async () => {
|
|
21
|
+
await expect(resolveEffectiveRetryLimit({ payloadRetryLimit: 7, dataDir: makeDataDir({ defaultRetryLimit: 2 }) })).resolves.toBe(7);
|
|
22
|
+
await expect(resolveEffectiveRetryLimit({ payloadRetryLimit: -1, dataDir: undefined })).rejects.toThrow('between 0 and 10');
|
|
23
|
+
await expect(resolveEffectiveRetryLimit({ payloadRetryLimit: 11, dataDir: undefined })).rejects.toThrow('between 0 and 10');
|
|
24
|
+
await expect(resolveEffectiveRetryLimit({ payloadRetryLimit: 2.5, dataDir: undefined })).rejects.toThrow('between 0 and 10');
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
test('sidecar default applies when no explicit value is given', async () => {
|
|
28
|
+
const dataDir = makeDataDir({ version: 1, defaultRetryLimit: 9 });
|
|
29
|
+
await expect(resolveEffectiveRetryLimit({ dataDir })).resolves.toBe(9);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
test(`no sidecar resolves to undefined so Pi stays authoritative (built-in fallback ${PI_FALLBACK_RETRY_LIMIT})`, async () => {
|
|
33
|
+
// No settings file at all.
|
|
34
|
+
await expect(resolveEffectiveRetryLimit({ dataDir: makeDataDir(undefined) })).resolves.toBeUndefined();
|
|
35
|
+
// File exists but has no retry key.
|
|
36
|
+
await expect(resolveEffectiveRetryLimit({ dataDir: makeDataDir({ version: 1 }) })).resolves.toBeUndefined();
|
|
37
|
+
// null is treated as "no override", matching the store's normalize().
|
|
38
|
+
await expect(resolveEffectiveRetryLimit({ dataDir: makeDataDir({ version: 1, defaultRetryLimit: null }) })).resolves.toBeUndefined();
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
test('a malformed sidecar value fails loudly instead of silently falling back', async () => {
|
|
42
|
+
const badTypes = [3.5, -1, 11, 'five'];
|
|
43
|
+
for (const defaultRetryLimit of badTypes) {
|
|
44
|
+
const dataDir = makeDataDir({ version: 1, defaultRetryLimit });
|
|
45
|
+
await expect(resolveEffectiveRetryLimit({ dataDir })).rejects.toThrow(/retry limit|JSON/i);
|
|
46
|
+
}
|
|
47
|
+
// Malformed JSON surfaces as a syntax error, not a silent undefined.
|
|
48
|
+
const dataDir = mkdtempSync(join(tmpdir(), 'pichamber-retry-'));
|
|
49
|
+
mkdirSync(join(dataDir, 'pi'), { recursive: true });
|
|
50
|
+
writeFileSync(join(dataDir, 'pi', 'settings.json'), '{ not json');
|
|
51
|
+
await expect(resolveEffectiveRetryLimit({ dataDir })).rejects.toThrow();
|
|
52
|
+
});
|
|
53
|
+
});
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { posix, win32 } from 'node:path';
|
|
2
|
+
|
|
3
|
+
const pathApiFor = (platform) => platform === 'win32' ? win32 : posix;
|
|
4
|
+
|
|
5
|
+
const pathKey = (filePath, platform = process.platform) => {
|
|
6
|
+
const normalized = pathApiFor(platform).normalize(filePath);
|
|
7
|
+
return platform === 'win32' ? normalized.toLowerCase() : normalized;
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Build the runtime-local lookup used to distinguish Pi skill loads from
|
|
12
|
+
* ordinary read calls. Skill names come from Pi's resource loader rather than
|
|
13
|
+
* from the SKILL.md parent directory because Pi allows those names to differ.
|
|
14
|
+
*/
|
|
15
|
+
export function createSkillReadClassifier({ cwd, skills, platform = process.platform }) {
|
|
16
|
+
const skillsByPath = new Map();
|
|
17
|
+
const pathApi = pathApiFor(platform);
|
|
18
|
+
for (const skill of Array.isArray(skills) ? skills : []) {
|
|
19
|
+
if (!skill || typeof skill.name !== 'string' || typeof skill.filePath !== 'string') continue;
|
|
20
|
+
const name = skill.name.trim();
|
|
21
|
+
if (!name || !skill.filePath.trim()) continue;
|
|
22
|
+
const absolutePath = pathApi.isAbsolute(skill.filePath) ? skill.filePath : pathApi.resolve(cwd, skill.filePath);
|
|
23
|
+
skillsByPath.set(pathKey(absolutePath, platform), { name });
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
return (toolName, args) => {
|
|
27
|
+
if (typeof toolName !== 'string' || toolName.toLowerCase() !== 'read' || !args || typeof args !== 'object') {
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
const rawPath = typeof args.path === 'string'
|
|
31
|
+
? args.path
|
|
32
|
+
: typeof args.file_path === 'string'
|
|
33
|
+
? args.file_path
|
|
34
|
+
: undefined;
|
|
35
|
+
if (!rawPath?.trim()) return undefined;
|
|
36
|
+
const absolutePath = pathApi.isAbsolute(rawPath) ? rawPath : pathApi.resolve(cwd, rawPath);
|
|
37
|
+
return skillsByPath.get(pathKey(absolutePath, platform));
|
|
38
|
+
};
|
|
39
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
|
|
4
|
+
import { createSkillReadClassifier } from './skill-read-classifier.js';
|
|
5
|
+
|
|
6
|
+
describe('skill read classifier', () => {
|
|
7
|
+
it('matches absolute and cwd-relative reads using Pi skill names', () => {
|
|
8
|
+
const cwd = join('/workspace', 'project');
|
|
9
|
+
const skillPath = join(cwd, '.agents', 'skills', 'directory-name', 'SKILL.md');
|
|
10
|
+
const classify = createSkillReadClassifier({
|
|
11
|
+
cwd,
|
|
12
|
+
skills: [{ name: 'frontmatter-name', filePath: skillPath }],
|
|
13
|
+
platform: 'linux',
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
expect(classify('read', { path: skillPath })).toEqual({ name: 'frontmatter-name' });
|
|
17
|
+
expect(classify('read', { path: join('.agents', 'skills', 'directory-name', 'SKILL.md') })).toEqual({ name: 'frontmatter-name' });
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
it('does not infer skills from filenames or classify other tools', () => {
|
|
21
|
+
const cwd = join('/workspace', 'project');
|
|
22
|
+
const classify = createSkillReadClassifier({
|
|
23
|
+
cwd,
|
|
24
|
+
skills: [{ name: 'known', filePath: join(cwd, '.agents', 'skills', 'known', 'SKILL.md') }],
|
|
25
|
+
platform: 'linux',
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
expect(classify('read', { path: join(cwd, 'notes', 'SKILL.md') })).toBeUndefined();
|
|
29
|
+
expect(classify('write', { path: join(cwd, '.agents', 'skills', 'known', 'SKILL.md') })).toBeUndefined();
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it('normalizes Windows path casing', () => {
|
|
33
|
+
const classify = createSkillReadClassifier({
|
|
34
|
+
cwd: 'C:\\Workspace',
|
|
35
|
+
skills: [{ name: 'review', filePath: 'C:\\Workspace\\skills\\review\\SKILL.md' }],
|
|
36
|
+
platform: 'win32',
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
expect(classify('READ', { file_path: 'c:\\workspace\\SKILLS\\review\\skill.md' })).toEqual({ name: 'review' });
|
|
40
|
+
});
|
|
41
|
+
});
|
|
@@ -26,6 +26,9 @@ const delay = (milliseconds) => new Promise((resolveDelay) => setTimeout(resolve
|
|
|
26
26
|
|
|
27
27
|
const rejectAfter = (promise, timeoutMs, code) => new Promise((resolvePromise, rejectPromise) => {
|
|
28
28
|
const timer = setTimeout(() => rejectPromise(new SessionDaemonClientError(code)), timeoutMs);
|
|
29
|
+
// The wrapped request owns its own timeout lifecycle; never hold process
|
|
30
|
+
// shutdown on this outer deadline.
|
|
31
|
+
timer.unref?.();
|
|
29
32
|
promise.then(
|
|
30
33
|
(value) => {
|
|
31
34
|
clearTimeout(timer);
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createAgentSessionFromServices,
|
|
3
|
+
createAgentSessionRuntime,
|
|
4
|
+
createAgentSessionServices,
|
|
5
|
+
getAgentDir,
|
|
6
|
+
SessionManager,
|
|
7
|
+
} from '@earendil-works/pi-coding-agent';
|
|
8
|
+
|
|
9
|
+
const DEFAULT_TIMEOUT_MS = 30_000;
|
|
10
|
+
|
|
11
|
+
const resolveAgentDir = () => {
|
|
12
|
+
const configured = typeof process.env.PICHAMBER_PI_AGENT_DIR === 'string'
|
|
13
|
+
? process.env.PICHAMBER_PI_AGENT_DIR.trim()
|
|
14
|
+
: '';
|
|
15
|
+
return configured || getAgentDir();
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
const readAssistantText = (messages) => {
|
|
19
|
+
const assistant = [...(Array.isArray(messages) ? messages : [])]
|
|
20
|
+
.reverse()
|
|
21
|
+
.find((message) => message?.role === 'assistant');
|
|
22
|
+
if (!assistant) return '';
|
|
23
|
+
if (typeof assistant.content === 'string') return assistant.content.trim();
|
|
24
|
+
if (!Array.isArray(assistant.content)) return '';
|
|
25
|
+
return assistant.content
|
|
26
|
+
.filter((part) => part?.type === 'text' && typeof part.text === 'string')
|
|
27
|
+
.map((part) => part.text)
|
|
28
|
+
.join('')
|
|
29
|
+
.trim();
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
export const createSmallModelGenerator = ({
|
|
33
|
+
agentDir = resolveAgentDir(),
|
|
34
|
+
timeoutMs = DEFAULT_TIMEOUT_MS,
|
|
35
|
+
createServices = createAgentSessionServices,
|
|
36
|
+
createSession = createAgentSessionFromServices,
|
|
37
|
+
createRuntime = createAgentSessionRuntime,
|
|
38
|
+
inMemorySession = (cwd) => SessionManager.inMemory(cwd),
|
|
39
|
+
} = {}) => async ({ directory, prompt, model }) => {
|
|
40
|
+
if (typeof directory !== 'string' || directory.length === 0) throw new Error('Small-model directory is required');
|
|
41
|
+
if (typeof prompt !== 'string' || prompt.trim().length === 0) throw new Error('Small-model prompt is required');
|
|
42
|
+
if (!model || typeof model.providerId !== 'string' || typeof model.modelId !== 'string') {
|
|
43
|
+
const error = new Error('No small model is configured');
|
|
44
|
+
error.code = 'SMALL_MODEL_UNCONFIGURED';
|
|
45
|
+
throw error;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const runtimeFactory = async ({ cwd, agentDir: runtimeAgentDir, sessionManager, sessionStartEvent }) => {
|
|
49
|
+
const services = await createServices({
|
|
50
|
+
cwd,
|
|
51
|
+
agentDir: runtimeAgentDir,
|
|
52
|
+
resourceLoaderOptions: { noExtensions: true },
|
|
53
|
+
});
|
|
54
|
+
const selectedModel = services.modelRuntime.getModel(model.providerId, model.modelId);
|
|
55
|
+
if (!selectedModel) {
|
|
56
|
+
const error = new Error('The configured small model is unavailable');
|
|
57
|
+
error.code = 'SMALL_MODEL_UNAVAILABLE';
|
|
58
|
+
throw error;
|
|
59
|
+
}
|
|
60
|
+
return {
|
|
61
|
+
...(await createSession({
|
|
62
|
+
services,
|
|
63
|
+
sessionManager,
|
|
64
|
+
sessionStartEvent,
|
|
65
|
+
model: selectedModel,
|
|
66
|
+
noTools: 'all',
|
|
67
|
+
})),
|
|
68
|
+
services,
|
|
69
|
+
diagnostics: services.diagnostics,
|
|
70
|
+
};
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
const runtime = await createRuntime(runtimeFactory, {
|
|
74
|
+
cwd: directory,
|
|
75
|
+
agentDir,
|
|
76
|
+
sessionManager: inMemorySession(directory),
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
let timer;
|
|
80
|
+
try {
|
|
81
|
+
await runtime.session.sendUserMessage(prompt.trim(), { expandPromptTemplates: false });
|
|
82
|
+
await Promise.race([
|
|
83
|
+
runtime.session.waitForIdle(),
|
|
84
|
+
new Promise((_, reject) => {
|
|
85
|
+
timer = setTimeout(() => {
|
|
86
|
+
void runtime.session.abort().catch(() => undefined);
|
|
87
|
+
const error = new Error('Small-model generation timed out');
|
|
88
|
+
error.code = 'SMALL_MODEL_TIMEOUT';
|
|
89
|
+
reject(error);
|
|
90
|
+
}, timeoutMs);
|
|
91
|
+
timer.unref?.();
|
|
92
|
+
}),
|
|
93
|
+
]);
|
|
94
|
+
const text = readAssistantText(runtime.session.messages);
|
|
95
|
+
if (!text) throw new Error('The small model returned an empty response');
|
|
96
|
+
return { text };
|
|
97
|
+
} finally {
|
|
98
|
+
clearTimeout(timer);
|
|
99
|
+
if (runtime.session.isStreaming) await runtime.session.abort().catch(() => undefined);
|
|
100
|
+
await runtime.dispose();
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
export const generateWithSmallModel = createSmallModelGenerator();
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import { createSmallModelGenerator } from './small-model-generation.js';
|
|
4
|
+
|
|
5
|
+
const createHarness = ({ waitForIdle = async () => undefined, timeoutMs = 100 } = {}) => {
|
|
6
|
+
const abort = vi.fn(async () => undefined);
|
|
7
|
+
const dispose = vi.fn(async () => undefined);
|
|
8
|
+
const session = {
|
|
9
|
+
sendUserMessage: vi.fn(async () => undefined),
|
|
10
|
+
waitForIdle,
|
|
11
|
+
abort,
|
|
12
|
+
isStreaming: false,
|
|
13
|
+
messages: [{ role: 'assistant', content: [{ type: 'text', text: 'fix-auth-timeout' }] }],
|
|
14
|
+
};
|
|
15
|
+
const selectedModel = { provider: 'provider', id: 'small' };
|
|
16
|
+
const createSession = vi.fn(async () => ({ session }));
|
|
17
|
+
const generate = createSmallModelGenerator({
|
|
18
|
+
agentDir: '/agent',
|
|
19
|
+
timeoutMs,
|
|
20
|
+
inMemorySession: () => ({ kind: 'memory' }),
|
|
21
|
+
createServices: async () => ({
|
|
22
|
+
modelRuntime: { getModel: () => selectedModel },
|
|
23
|
+
diagnostics: [],
|
|
24
|
+
}),
|
|
25
|
+
createSession,
|
|
26
|
+
createRuntime: async (factory, options) => ({
|
|
27
|
+
...(await factory({
|
|
28
|
+
cwd: options.cwd,
|
|
29
|
+
agentDir: options.agentDir,
|
|
30
|
+
sessionManager: options.sessionManager,
|
|
31
|
+
})),
|
|
32
|
+
dispose,
|
|
33
|
+
}),
|
|
34
|
+
});
|
|
35
|
+
return { abort, createSession, dispose, generate, selectedModel, session };
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
describe('small-model generation', () => {
|
|
39
|
+
it('uses an in-memory no-tools session and returns only assistant text', async () => {
|
|
40
|
+
const harness = createHarness();
|
|
41
|
+
await expect(harness.generate({
|
|
42
|
+
directory: '/repo',
|
|
43
|
+
prompt: 'Name this task',
|
|
44
|
+
model: { providerId: 'provider', modelId: 'small' },
|
|
45
|
+
})).resolves.toEqual({ text: 'fix-auth-timeout' });
|
|
46
|
+
|
|
47
|
+
expect(harness.createSession).toHaveBeenCalledWith(expect.objectContaining({
|
|
48
|
+
model: harness.selectedModel,
|
|
49
|
+
noTools: 'all',
|
|
50
|
+
sessionManager: { kind: 'memory' },
|
|
51
|
+
}));
|
|
52
|
+
expect(harness.session.sendUserMessage).toHaveBeenCalledWith('Name this task', { expandPromptTemplates: false });
|
|
53
|
+
expect(harness.dispose).toHaveBeenCalledOnce();
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
it('aborts and disposes a timed-out generation', async () => {
|
|
57
|
+
const harness = createHarness({ waitForIdle: () => new Promise(() => {}), timeoutMs: 5 });
|
|
58
|
+
await expect(harness.generate({
|
|
59
|
+
directory: '/repo',
|
|
60
|
+
prompt: 'Name this task',
|
|
61
|
+
model: { providerId: 'provider', modelId: 'small' },
|
|
62
|
+
})).rejects.toThrow('timed out');
|
|
63
|
+
expect(harness.abort).toHaveBeenCalledOnce();
|
|
64
|
+
expect(harness.dispose).toHaveBeenCalledOnce();
|
|
65
|
+
});
|
|
66
|
+
});
|
|
@@ -1190,6 +1190,16 @@ export const createPreviewProxyRuntime = ({
|
|
|
1190
1190
|
createProxyMiddleware,
|
|
1191
1191
|
responseInterceptor,
|
|
1192
1192
|
}) => {
|
|
1193
|
+
// Preview tokens gate arbitrary loopback proxying, so compare in constant time.
|
|
1194
|
+
// Length mismatch returns false without comparing (timingSafeEqual throws).
|
|
1195
|
+
const tokensMatch = (provided, expected) => {
|
|
1196
|
+
if (typeof provided !== 'string' || provided.length === 0) return false;
|
|
1197
|
+
const a = Buffer.from(provided);
|
|
1198
|
+
const b = Buffer.from(expected);
|
|
1199
|
+
if (a.length !== b.length) return false;
|
|
1200
|
+
return crypto.timingSafeEqual(a, b);
|
|
1201
|
+
};
|
|
1202
|
+
|
|
1193
1203
|
const targets = new Map();
|
|
1194
1204
|
let sweepTimer = null;
|
|
1195
1205
|
|
|
@@ -1247,7 +1257,7 @@ export const createPreviewProxyRuntime = ({
|
|
|
1247
1257
|
|
|
1248
1258
|
const cookies = parseCookieHeader(req.headers?.cookie);
|
|
1249
1259
|
const token = parsed.searchParams.get(TOKEN_QUERY_PARAM) || cookies.get(TOKEN_COOKIE_NAME) || '';
|
|
1250
|
-
if (!token || token
|
|
1260
|
+
if (!token || !tokensMatch(token, entry.token)) {
|
|
1251
1261
|
return { ok: false, status: 403, code: 'invalid-token', error: 'Preview token missing' };
|
|
1252
1262
|
}
|
|
1253
1263
|
|