@cortex-agent/server 2026.9.15 → 2026.9.25
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 +3 -2
- package/defaults/config/hooks/08-agents-md-injector-post-tool.json +10 -0
- package/defaults/config/hooks/{10-cortex-md-injector-session-start.json → 10-agents-md-injector-session-start.json} +3 -3
- package/defaults/config/hooks/{CORTEX.md → AGENTS.md} +2 -2
- package/defaults/config/thread-templates/agents/creative.json +17 -0
- package/defaults/hooks/{CORTEX.md → AGENTS.md} +1 -1
- package/defaults/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
- package/defaults/hooks/cortex-hook-api.mjs +2 -2
- package/defaults/hooks/new-session-hook.mjs +2 -2
- package/defaults/hooks/rules-loader.mjs +2 -2
- package/defaults/hooks/status-md-guard.mjs +8 -8
- package/defaults/hooks/task-status-check.mjs +18 -76
- package/defaults/hooks/tasks-yaml-guard.mjs +2 -2
- package/defaults/plugins/cortex-feishu/skills/feishu-doc/SKILL.md +1 -1
- package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +2 -2
- package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +4 -4
- package/defaults/plugins/cortex-system/skills/task/SKILL.md +1 -1
- package/defaults/prompts/systemPrompts/creative.md +13 -0
- package/defaults/prompts/systemPrompts/direct.md +1 -1
- package/defaults/rules/{cortex-md.md → agents-md.md} +4 -4
- package/defaults/rules/decision-records.md +1 -1
- package/defaults/rules/meta-conventions.md +4 -4
- package/defaults/rules/mission-md.md +1 -1
- package/dist/agent-adapter/claude/adapter.d.ts +12 -0
- package/dist/agent-adapter/claude/adapter.js +19 -1
- package/dist/agent-adapter/claude/hooks-builder.js +2 -2
- package/dist/agent-adapter/claude/spawn-args.d.ts +7 -0
- package/dist/agent-adapter/claude/spawn-args.js +14 -0
- package/dist/agent-adapter/claude/turn-machine.d.ts +11 -0
- package/dist/agent-adapter/claude/turn-machine.js +46 -5
- package/dist/agent-adapter/normalize/prompt-builder.d.ts +16 -1
- package/dist/agent-adapter/normalize/prompt-builder.js +24 -6
- package/dist/agent-adapter/pi/child-runner.d.ts +4 -2
- package/dist/agent-adapter/pi/child-runner.js +5 -1
- package/dist/agent-adapter/pi/event-parser.d.ts +3 -2
- package/dist/agent-adapter/pi/event-parser.js +46 -2
- package/dist/agent-adapter/pi/extensions.d.ts +7 -1
- package/dist/agent-adapter/pi/extensions.js +10 -3
- package/dist/agent-adapter/pi/mcp-bridge.js +8 -8
- package/dist/agent-adapter/pi/pi-session.js +5 -0
- package/dist/agent-adapter/pi/runtime.js +3 -0
- package/dist/agent-adapter/pi/session-options.js +5 -1
- package/dist/agent-adapter/pi/subagent.d.ts +15 -3
- package/dist/agent-adapter/pi/subagent.js +18 -0
- package/dist/agent-adapter/pi/tool-shims.d.ts +6 -1
- package/dist/agent-adapter/pi/tool-shims.js +34 -1
- package/dist/agent-adapter/types.d.ts +6 -0
- package/dist/core/agents/subagent/types.d.ts +3 -0
- package/dist/core/config-generator.js +17 -2
- package/dist/core/debug-mode.d.ts +11 -10
- package/dist/core/debug-mode.js +12 -18
- package/dist/core/exec-async.d.ts +26 -0
- package/dist/core/exec-async.js +47 -0
- package/dist/core/locales/en.d.ts +14 -1
- package/dist/core/locales/slices/commands.d.ts +12 -1
- package/dist/core/locales/slices/commands.js +24 -2
- package/dist/core/locales/slices/startup.d.ts +2 -0
- package/dist/core/locales/slices/startup.js +4 -0
- package/dist/core/mcp-tool-gate.js +1 -0
- package/dist/core/media-types.d.ts +10 -0
- package/dist/core/media-types.js +34 -0
- package/dist/core/platform-settings-spec.js +1 -1
- package/dist/core/rebuild-progress.d.ts +58 -0
- package/dist/core/rebuild-progress.js +103 -0
- package/dist/core/resilient-watch.js +5 -3
- package/dist/core/run-registry.d.ts +7 -0
- package/dist/core/run-registry.js +6 -0
- package/dist/core/settings-spec.d.ts +21 -0
- package/dist/core/settings-spec.js +28 -1
- package/dist/core/types/agent-types.d.ts +3 -1
- package/dist/core/types/thread-types.d.ts +23 -4
- package/dist/core/utils.d.ts +1 -1
- package/dist/core/utils.js +1 -1
- package/dist/domain/agents/agent-state.d.ts +7 -0
- package/dist/domain/agents/agent-state.js +9 -1
- package/dist/domain/agents/agent-switch.d.ts +38 -0
- package/dist/domain/agents/agent-switch.js +106 -0
- package/dist/domain/agents/config.d.ts +20 -2
- package/dist/domain/agents/config.js +58 -4
- package/dist/domain/agents/index.d.ts +1 -0
- package/dist/domain/agents/index.js +1 -0
- package/dist/domain/agents/profile-manager.d.ts +6 -0
- package/dist/domain/agents/profile-manager.js +14 -1
- package/dist/domain/executions/registry.d.ts +3 -2
- package/dist/domain/executions/registry.js +84 -10
- package/dist/domain/mcp/bundled-server.js +4 -3
- package/dist/domain/mcp/feishu/file.js +37 -18
- package/dist/domain/mcp/feishu/types.d.ts +3 -0
- package/dist/domain/mcp/feishu-server.js +1 -1
- package/dist/domain/mcp/tools/{cortex-md.d.ts → agents-md.d.ts} +6 -6
- package/dist/domain/mcp/tools/{cortex-md.js → agents-md.js} +6 -6
- package/dist/domain/mcp/tools/remote-file.d.ts +20 -0
- package/dist/domain/mcp/tools/remote-file.js +44 -0
- package/dist/domain/mcp/tools/slack.d.ts +2 -0
- package/dist/domain/mcp/tools/slack.js +22 -7
- package/dist/domain/mcp/tools/task-ops.js +5 -13
- package/dist/domain/mcp/tools/ui-file.js +23 -10
- package/dist/domain/mcp/tools/waitpoint.d.ts +3 -0
- package/dist/domain/mcp/tools/waitpoint.js +122 -0
- package/dist/domain/memory/agents-md-injector.d.ts +24 -0
- package/dist/domain/memory/{cortex-md-injector.js → agents-md-injector.js} +10 -7
- package/dist/domain/plugins/runtime.js +1 -1
- package/dist/domain/plugins/skill-projection.d.ts +8 -2
- package/dist/domain/plugins/skill-projection.js +76 -19
- package/dist/domain/projects/project-store.d.ts +1 -1
- package/dist/domain/projects/project-store.js +3 -3
- package/dist/domain/remote/client-bootstrap.js +1 -1
- package/dist/domain/remote/client-hot-reload.d.ts +1 -1
- package/dist/domain/remote/client-hot-reload.js +30 -24
- package/dist/domain/remote/client-manager.js +39 -119
- package/dist/domain/remote/cortex-client-config.d.ts +1 -1
- package/dist/domain/remote/cortex-client-config.js +1 -1
- package/dist/domain/remote/device-file.d.ts +51 -0
- package/dist/domain/remote/device-file.js +193 -0
- package/dist/domain/remote/device-port.js +3 -0
- package/dist/domain/remote/reverse-stream.d.ts +18 -7
- package/dist/domain/remote/reverse-stream.js +19 -6
- package/dist/domain/runs/engine-spec.js +4 -0
- package/dist/domain/runs/request.d.ts +6 -0
- package/dist/domain/runs/run.js +1 -0
- package/dist/domain/runs/spec-loader.d.ts +4 -3
- package/dist/domain/runs/spec-loader.js +4 -3
- package/dist/domain/scheduling/jobs/sync-public.js +6 -6
- package/dist/domain/scheduling/scheduler.js +14 -12
- package/dist/domain/sessions/session-lifecycle.d.ts +5 -0
- package/dist/domain/sessions/session-lifecycle.js +13 -1
- package/dist/domain/system/rebuild-hold.d.ts +44 -0
- package/dist/domain/system/rebuild-hold.js +91 -0
- package/dist/domain/system/server-update-check.d.ts +2 -1
- package/dist/domain/system/server-update-check.js +15 -13
- package/dist/domain/tasks/archiver.js +21 -13
- package/dist/domain/tasks/claim-recovery.js +2 -2
- package/dist/domain/tasks/dispatch-utils.d.ts +10 -1
- package/dist/domain/tasks/dispatch-utils.js +46 -1
- package/dist/domain/tasks/dispatcher.js +4 -5
- package/dist/domain/tasks/mutator.d.ts +2 -2
- package/dist/domain/tasks/mutator.js +62 -61
- package/dist/domain/tasks/system/task-cli.js +2 -2
- package/dist/domain/tasks/system/task-completion.d.ts +7 -2
- package/dist/domain/tasks/system/task-completion.js +69 -6
- package/dist/domain/tasks/system/task-lifecycle-edit.d.ts +6 -1
- package/dist/domain/tasks/system/task-lifecycle-edit.js +21 -2
- package/dist/domain/tasks/system/task-lock.d.ts +23 -0
- package/dist/domain/tasks/system/task-lock.js +29 -1
- package/dist/domain/tasks/system/task-mutations.d.ts +14 -1
- package/dist/domain/tasks/system/task-mutations.js +25 -2
- package/dist/domain/tasks/system/task-state.d.ts +12 -1
- package/dist/domain/tasks/system/task-state.js +20 -3
- package/dist/domain/threads/prompt-builder.d.ts +9 -6
- package/dist/domain/threads/prompt-builder.js +28 -10
- package/dist/domain/threads/runner.js +10 -4
- package/dist/domain/threads/state-machine.js +15 -11
- package/dist/domain/threads/template-loader.js +6 -4
- package/dist/domain/threads/template-validate.d.ts +43 -6
- package/dist/domain/threads/template-validate.js +12 -0
- package/dist/domain/ui-service/app-router.d.ts +34 -3
- package/dist/domain/ui-service/app-router.js +9 -14
- package/dist/domain/ui-service/input-schemas.d.ts +28 -5
- package/dist/domain/ui-service/input-schemas.js +24 -9
- package/dist/domain/ui-service/mutate/platform-settings.js +1 -1
- package/dist/domain/ui-service/mutate/sessions.d.ts +6 -1
- package/dist/domain/ui-service/mutate/sessions.js +54 -0
- package/dist/domain/ui-service/mutate/tasks.js +4 -3
- package/dist/domain/ui-service/mutate/waitpoints.d.ts +2 -0
- package/dist/domain/ui-service/mutate/waitpoints.js +20 -0
- package/dist/domain/ui-service/platform-settings.js +1 -1
- package/dist/domain/ui-service/plugins-shared.js +1 -1
- package/dist/domain/ui-service/query/config.js +20 -2
- package/dist/domain/ui-service/query/executions.js +0 -2
- package/dist/domain/ui-service/query/machine-detail.js +3 -8
- package/dist/domain/ui-service/query/memory.js +29 -35
- package/dist/domain/ui-service/query/sessions.js +96 -12
- package/dist/domain/ui-service/query/system.js +19 -0
- package/dist/domain/ui-service/query/threads.js +1 -54
- package/dist/domain/ui-service/query/waitpoints.d.ts +30 -0
- package/dist/domain/ui-service/query/waitpoints.js +117 -0
- package/dist/domain/ui-service/query-input-schemas.d.ts +4 -0
- package/dist/domain/ui-service/query-input-schemas.js +5 -0
- package/dist/domain/ui-service/trpc.js +1 -1
- package/dist/domain/ui-service/types.d.ts +229 -51
- package/dist/domain/ui-service/types.js +1 -1
- package/dist/domain/ui-service/ui-service.js +8 -31
- package/dist/domain/waitpoints/notices.d.ts +21 -0
- package/dist/domain/waitpoints/notices.js +115 -0
- package/dist/domain/waitpoints/service.d.ts +91 -0
- package/dist/domain/waitpoints/service.js +243 -0
- package/dist/entry/app.js +52 -11
- package/dist/entry/auth-login-cli.js +1 -1
- package/dist/entry/auth-login-terminal.js +1 -1
- package/dist/entry/daemon-notice.d.ts +10 -1
- package/dist/entry/daemon-notice.js +16 -1
- package/dist/entry/daemon.d.ts +43 -2
- package/dist/entry/daemon.js +163 -9
- package/dist/entry/init-auth.js +1 -1
- package/dist/entry/init.js +6 -6
- package/dist/entry/signal-cli.d.ts +30 -0
- package/dist/entry/signal-cli.js +207 -0
- package/dist/entry/start-ui-http.d.ts +1 -1
- package/dist/entry/start-ui-http.js +2 -2
- package/dist/events/event-types.d.ts +0 -7
- package/dist/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
- package/dist/hooks/cortex-hook-api.mjs +2 -2
- package/dist/hooks/new-session-hook.mjs +2 -2
- package/dist/hooks/rules-loader.mjs +2 -2
- package/dist/hooks/status-md-guard.mjs +8 -8
- package/dist/hooks/task-status-check.mjs +18 -76
- package/dist/hooks/tasks-yaml-guard.mjs +2 -2
- package/dist/orchestration/agent-file-send.d.ts +9 -0
- package/dist/orchestration/agent-file-send.js +21 -2
- package/dist/orchestration/agent-runner.d.ts +3 -2
- package/dist/orchestration/agent-runner.js +33 -12
- package/dist/orchestration/attachments-store.d.ts +31 -0
- package/dist/orchestration/attachments-store.js +184 -0
- package/dist/orchestration/conversation-request.d.ts +37 -0
- package/dist/orchestration/conversation-request.js +91 -22
- package/dist/orchestration/interactions/plan-approvals.js +1 -1
- package/dist/orchestration/mid-turn-inject.d.ts +3 -0
- package/dist/orchestration/mid-turn-inject.js +9 -4
- package/dist/orchestration/outputs-store.d.ts +11 -0
- package/dist/orchestration/outputs-store.js +32 -6
- package/dist/orchestration/resume-dispatcher.js +4 -2
- package/dist/orchestration/routing/commands/mode.js +114 -63
- package/dist/orchestration/routing/file-handler.d.ts +23 -2
- package/dist/orchestration/routing/file-handler.js +22 -5
- package/dist/orchestration/routing/webhook.js +193 -39
- package/dist/orchestration/session-gateway.d.ts +1 -1
- package/dist/orchestration/session-gateway.js +1 -0
- package/dist/orchestration/thread-executor.d.ts +2 -0
- package/dist/orchestration/thread-executor.js +24 -1
- package/dist/orchestration/thread-input.d.ts +3 -2
- package/dist/orchestration/thread-input.js +8 -9
- package/dist/orchestration/turn/turn-prep.d.ts +15 -1
- package/dist/orchestration/turn/turn-prep.js +19 -8
- package/dist/orchestration/turn/turn.js +1 -0
- package/dist/orchestration/waitpoint-ingress.d.ts +41 -0
- package/dist/orchestration/waitpoint-ingress.js +172 -0
- package/dist/orchestration/waitpoint-notifier.d.ts +21 -0
- package/dist/orchestration/waitpoint-notifier.js +119 -0
- package/dist/orchestration/waitpoint-remote-drain.d.ts +20 -0
- package/dist/orchestration/waitpoint-remote-drain.js +147 -0
- package/dist/orchestration/waitpoint-sweep.d.ts +42 -0
- package/dist/orchestration/waitpoint-sweep.js +87 -0
- package/dist/platform/adapters/feishu-image.d.ts +19 -0
- package/dist/platform/adapters/feishu-image.js +71 -0
- package/dist/platform/adapters/feishu.d.ts +2 -0
- package/dist/platform/adapters/feishu.js +26 -16
- package/dist/platform/ui-http/listening-ports.d.ts +1 -1
- package/dist/platform/ui-http/listening-ports.js +1 -1
- package/dist/platform/ui-http/ui-session.js +1 -1
- package/dist/store/conversation-display-projection.d.ts +9 -1
- package/dist/store/conversation-display-projection.js +13 -6
- package/dist/store/conversation-history-reader.d.ts +19 -0
- package/dist/store/conversation-history-reader.js +163 -44
- package/dist/store/conversation-history-repo.d.ts +37 -10
- package/dist/store/conversation-history-repo.js +161 -139
- package/dist/store/conversation-ledger-repo.js +1 -1
- package/dist/store/execution-repo.d.ts +1 -19
- package/dist/store/execution-repo.js +1 -18
- package/dist/store/project-notes-repo.js +11 -2
- package/dist/store/prompt-migration-replacements.js +1 -1
- package/dist/store/session-registry-import.js +1 -1
- package/dist/store/session-registry-journal.d.ts +4 -0
- package/dist/store/session-registry-journal.js +5 -1
- package/dist/store/session-registry-repo.d.ts +2 -1
- package/dist/store/session-registry-repo.js +3 -1
- package/dist/store/task-repo.d.ts +6 -3
- package/dist/store/task-repo.js +26 -10
- package/dist/store/version-migrations.d.ts +13 -3
- package/dist/store/version-migrations.js +254 -24
- package/dist/store/waitpoint-repo.d.ts +108 -0
- package/dist/store/waitpoint-repo.js +94 -0
- package/package.json +3 -2
- package/web/dist/AGENTS.md +10 -0
- package/web/dist/assets/index-B1dBi8Za.css +1 -0
- package/web/dist/assets/{index-CEZ0DSei.js → index-BAeLybF0.js} +1 -1
- package/web/dist/assets/index-BcQI8Fh5.js +445 -0
- package/web/dist/index.html +12 -4
- package/web/dist/theme.css +211 -40
- package/defaults/config/hooks/08-cortex-md-injector-post-tool.json +0 -10
- package/dist/domain/executions/log-tailer.d.ts +0 -71
- package/dist/domain/executions/log-tailer.js +0 -194
- package/dist/domain/memory/cortex-md-injector.d.ts +0 -24
- package/dist/domain/memory/cortex-md-scanner.d.ts +0 -10
- package/dist/domain/memory/cortex-md-scanner.js +0 -66
- package/dist/domain/remote/cortex-client.d.ts +0 -1
- package/dist/domain/remote/cortex-client.js +0 -662
- package/dist/domain/tasks/system/cortex-run.d.ts +0 -25
- package/dist/domain/tasks/system/cortex-run.js +0 -360
- package/web/dist/assets/index-CRDJo39X.css +0 -1
- package/web/dist/assets/index-DjuPJVZE.js +0 -444
- /package/defaults/{CORTEX.md → AGENTS.md} +0 -0
- /package/defaults/config/{CORTEX.md → AGENTS.md} +0 -0
- /package/defaults/context/{CORTEX.md → AGENTS.md} +0 -0
- /package/defaults/context/ideas/{CORTEX.md → AGENTS.md} +0 -0
- /package/defaults/context/projects/{CORTEX.md → AGENTS.md} +0 -0
- /package/defaults/context/scans/{CORTEX.md → AGENTS.md} +0 -0
- /package/defaults/context/user/{CORTEX.md → AGENTS.md} +0 -0
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// input: a local file a Feishu send is about to carry
|
|
2
|
+
// output: an image_key when Feishu can show it inline in the chat, null when it has to go as a file
|
|
3
|
+
// pos: platform/adapters — shared by the Feishu adapter's `uploadFile` and the `feishu_send_file`
|
|
4
|
+
// MCP tool, the two independent implementations of "send this file to Feishu". Both used to
|
|
5
|
+
// call `im/v1/files` unconditionally, so a screenshot the agent produced arrived as a
|
|
6
|
+
// download card: the user had to tap it to see their own picture, and it never previewed in
|
|
7
|
+
// a notification or on mobile. `im/v1/images` was never called at all.
|
|
8
|
+
import { createReadStream, promises as fs } from 'fs';
|
|
9
|
+
import { sniffImageMime } from '../../core/media-types.js';
|
|
10
|
+
import { createLogger } from '../../core/log.js';
|
|
11
|
+
const log = createLogger('feishu-image');
|
|
12
|
+
/** Feishu rejects an image upload above 10 MB (im/v1/images). Anything larger goes as a file. */
|
|
13
|
+
export const FEISHU_IMAGE_MAX_BYTES = 10 * 1024 * 1024;
|
|
14
|
+
/** Bytes read to identify the file's real type. */
|
|
15
|
+
const SNIFF_BYTES = 16;
|
|
16
|
+
/** The formats Feishu renders inline in a chat. Deliberately a subset of what it accepts: a format
|
|
17
|
+
* we cannot identify from its first bytes is safer as a file than as a rejected upload. */
|
|
18
|
+
const INLINE_IMAGE_MIMES = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/bmp']);
|
|
19
|
+
/**
|
|
20
|
+
* The mime Feishu would show inline for this file, or null when it must be sent as a file.
|
|
21
|
+
*
|
|
22
|
+
* Decided from the bytes, not the extension: the agent writes `chart.png` with whatever its plotting
|
|
23
|
+
* library produced, and a mislabelled file that is uploaded as an image is rejected by the API.
|
|
24
|
+
*/
|
|
25
|
+
export async function inlineImageMime(filePath, size) {
|
|
26
|
+
if (!(size > 0) || size > FEISHU_IMAGE_MAX_BYTES)
|
|
27
|
+
return null;
|
|
28
|
+
let handle;
|
|
29
|
+
try {
|
|
30
|
+
handle = await fs.open(filePath, 'r');
|
|
31
|
+
const buf = Buffer.alloc(SNIFF_BYTES);
|
|
32
|
+
const { bytesRead } = await handle.read(buf, 0, SNIFF_BYTES, 0);
|
|
33
|
+
const mime = sniffImageMime(buf.subarray(0, bytesRead));
|
|
34
|
+
return mime && INLINE_IMAGE_MIMES.has(mime) ? mime : null;
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
finally {
|
|
40
|
+
await handle?.close().catch(() => undefined);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Upload `filePath` as a chat image and return its `image_key`, or null when the caller should send
|
|
45
|
+
* it as a file instead.
|
|
46
|
+
*
|
|
47
|
+
* Null is the ordinary outcome for a non-image, an oversized image — and for an upload the app is
|
|
48
|
+
* not allowed to make: `im/v1/images` needs the `im:resource` scope, which an app registered before
|
|
49
|
+
* Cortex ever sent an image will not have. A missing scope must degrade to the previous behaviour,
|
|
50
|
+
* never lose the send.
|
|
51
|
+
*/
|
|
52
|
+
export async function uploadFeishuImage(client, filePath, size) {
|
|
53
|
+
if (!(await inlineImageMime(filePath, size)))
|
|
54
|
+
return null;
|
|
55
|
+
try {
|
|
56
|
+
const res = await client.im.v1.image.create({
|
|
57
|
+
data: { image_type: 'message', image: createReadStream(filePath) },
|
|
58
|
+
});
|
|
59
|
+
if (res && typeof res.code === 'number' && res.code !== 0) {
|
|
60
|
+
throw new Error(`Feishu API error ${res.code}: ${res.msg ?? 'unknown'}`);
|
|
61
|
+
}
|
|
62
|
+
const key = res?.data?.image_key ?? res?.image_key;
|
|
63
|
+
if (key)
|
|
64
|
+
return key;
|
|
65
|
+
log.warn(`image upload returned no image_key for ${filePath}; sending it as a file`);
|
|
66
|
+
}
|
|
67
|
+
catch (e) {
|
|
68
|
+
log.warn(`image upload failed for ${filePath} (${e.message}); sending it as a file`);
|
|
69
|
+
}
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
@@ -50,6 +50,8 @@ export declare class FeishuAdapter implements PlatformAdapter {
|
|
|
50
50
|
markQueued(ref: MessageRef): Promise<void>;
|
|
51
51
|
unmarkQueued(ref: MessageRef): Promise<void>;
|
|
52
52
|
uploadFile(destination: Destination, filePath: string, opts?: FileUploadOpts): Promise<void>;
|
|
53
|
+
/** Upload as a chat file and return its file_key. */
|
|
54
|
+
private uploadFeishuFile;
|
|
53
55
|
downloadFile(fileRef: PlatformFileRef, destDir: string): Promise<DownloadedFile>;
|
|
54
56
|
getPermalink(_ref: MessageRef): Promise<string | null>;
|
|
55
57
|
openOutputStream(destination: Destination, opts?: OpenOutputStreamOpts): OutputStream;
|
|
@@ -7,6 +7,7 @@ import { updateSettings } from '../../core/settings.js';
|
|
|
7
7
|
import { FeishuOutputStream } from './feishu-output-stream.js';
|
|
8
8
|
import { configureFeishuHttp } from './feishu-http.js';
|
|
9
9
|
import { ProjectConduitsStore } from './project-conduits.js';
|
|
10
|
+
import { uploadFeishuImage } from './feishu-image.js';
|
|
10
11
|
import { reactionFailureReason, shouldWarnReactionFailure } from '../utils/reaction-diagnostics.js';
|
|
11
12
|
const log = createLogger('feishu');
|
|
12
13
|
/**
|
|
@@ -316,26 +317,21 @@ export class FeishuAdapter {
|
|
|
316
317
|
if (!destResolved.channel) {
|
|
317
318
|
return;
|
|
318
319
|
}
|
|
319
|
-
const { resolved: fileResolved } = this.resolveFilePath(filePath);
|
|
320
|
+
const { resolved: fileResolved, size } = this.resolveFilePath(filePath);
|
|
320
321
|
const fileName = opts?.filename || path.basename(fileResolved);
|
|
321
|
-
//
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
}
|
|
328
|
-
|
|
329
|
-
const fileKey = uploadRes?.data?.file_key;
|
|
330
|
-
if (!fileKey)
|
|
331
|
-
throw new Error('Feishu file upload failed: no file_key returned');
|
|
332
|
-
// Send file message
|
|
333
|
-
const msgContent = JSON.stringify({ file_key: fileKey });
|
|
322
|
+
// A picture the user can see beats a download card. Feishu shows an `image` message inline (and
|
|
323
|
+
// in the notification preview); anything it cannot — a non-image, an image over 10 MB, an app
|
|
324
|
+
// without the `im:resource` scope — falls back to the file card this always used to send.
|
|
325
|
+
const imageKey = await uploadFeishuImage(this.client, fileResolved, size);
|
|
326
|
+
const msgType = imageKey ? 'image' : 'file';
|
|
327
|
+
const msgContent = imageKey
|
|
328
|
+
? JSON.stringify({ image_key: imageKey })
|
|
329
|
+
: JSON.stringify({ file_key: await this.uploadFeishuFile(fileResolved, fileName) });
|
|
334
330
|
const threadId = opts?.threadId;
|
|
335
331
|
if (threadId) {
|
|
336
332
|
await this.client.im.v1.message.reply({
|
|
337
333
|
path: { message_id: threadId },
|
|
338
|
-
data: { msg_type:
|
|
334
|
+
data: { msg_type: msgType, content: msgContent },
|
|
339
335
|
});
|
|
340
336
|
}
|
|
341
337
|
else {
|
|
@@ -343,12 +339,26 @@ export class FeishuAdapter {
|
|
|
343
339
|
params: { receive_id_type: 'chat_id' },
|
|
344
340
|
data: {
|
|
345
341
|
receive_id: destResolved.channel,
|
|
346
|
-
msg_type:
|
|
342
|
+
msg_type: msgType,
|
|
347
343
|
content: msgContent,
|
|
348
344
|
},
|
|
349
345
|
});
|
|
350
346
|
}
|
|
351
347
|
}
|
|
348
|
+
/** Upload as a chat file and return its file_key. */
|
|
349
|
+
async uploadFeishuFile(fileResolved, fileName) {
|
|
350
|
+
const uploadRes = await this.client.im.v1.file.create({
|
|
351
|
+
data: {
|
|
352
|
+
file_type: this.inferFeishuFileType(fileName),
|
|
353
|
+
file_name: fileName,
|
|
354
|
+
file: fs.readFileSync(fileResolved),
|
|
355
|
+
},
|
|
356
|
+
});
|
|
357
|
+
const fileKey = uploadRes?.data?.file_key;
|
|
358
|
+
if (!fileKey)
|
|
359
|
+
throw new Error('Feishu file upload failed: no file_key returned');
|
|
360
|
+
return fileKey;
|
|
361
|
+
}
|
|
352
362
|
async downloadFile(fileRef, destDir) {
|
|
353
363
|
const raw = fileRef.raw || {};
|
|
354
364
|
const messageId = raw.message_id;
|
|
@@ -24,7 +24,7 @@ export declare const MIN_FORWARDABLE_PORT = 1024;
|
|
|
24
24
|
*
|
|
25
25
|
* `MSYS_NO_PATHCONV=1` is required because commands reach a Windows device through git-bash, which
|
|
26
26
|
* rewrites the `/FO` switch into a filesystem path (`C:/Program Files/Git/FO`) and makes tasklist
|
|
27
|
-
* fail. Verified on
|
|
27
|
+
* fail. Verified on a Windows device.
|
|
28
28
|
*/
|
|
29
29
|
export declare const WINDOWS_LISTENER_COMMAND = "netstat -ano; echo '#--tasklist--#'; MSYS_NO_PATHCONV=1 tasklist /FO CSV /NH";
|
|
30
30
|
/**
|
|
@@ -27,7 +27,7 @@ const TASKLIST_MARKER = '#--tasklist--#';
|
|
|
27
27
|
*
|
|
28
28
|
* `MSYS_NO_PATHCONV=1` is required because commands reach a Windows device through git-bash, which
|
|
29
29
|
* rewrites the `/FO` switch into a filesystem path (`C:/Program Files/Git/FO`) and makes tasklist
|
|
30
|
-
* fail. Verified on
|
|
30
|
+
* fail. Verified on a Windows device.
|
|
31
31
|
*/
|
|
32
32
|
export const WINDOWS_LISTENER_COMMAND = `netstat -ano; echo '${TASKLIST_MARKER}'; MSYS_NO_PATHCONV=1 tasklist /FO CSV /NH`;
|
|
33
33
|
/** Foreign address of a listening socket, in both families. Locale-independent — unlike the state
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
// HttpOnly cookie; every later request is admitted by that id instead of the token, so the
|
|
6
6
|
// secret itself never enters the page's JavaScript. Ids are 32 random bytes with an
|
|
7
7
|
// ABSOLUTE expiry (verify never renews — that keeps verify write-free), persisted to
|
|
8
|
-
//
|
|
8
|
+
// STORE_DIR/ui-sessions.json at 0600 so a daemon restart does not log every browser out.
|
|
9
9
|
// A session id is bearer-equivalent but strictly weaker than the token: the auth gate never
|
|
10
10
|
// accepts it on the /forward WebSocket upgrade (see ui-http-server.ts).
|
|
11
11
|
import * as crypto from 'crypto';
|
|
@@ -16,12 +16,20 @@ export interface CompactConversationHistory {
|
|
|
16
16
|
events: CompactConversationEvent[];
|
|
17
17
|
committedSourceIds: string[];
|
|
18
18
|
subagentSummaries: CompactSubagentSummary[];
|
|
19
|
+
/** Server-internal, positionally aligned with `events`: the source row's revision. Present only
|
|
20
|
+
* when the caller supplied revisions; it is what lets a transcript read answer "since X". */
|
|
21
|
+
eventRevs?: number[];
|
|
19
22
|
}
|
|
20
23
|
export interface SubagentConversationHistory {
|
|
21
24
|
sessionId: string;
|
|
22
25
|
subagentId: string;
|
|
23
26
|
events: CompactConversationEvent[];
|
|
24
27
|
}
|
|
25
|
-
|
|
28
|
+
/**
|
|
29
|
+
* Fold a parsed history into the compact read model. `sourceRevs` is positional against
|
|
30
|
+
* `history.events`; supply it and the result carries the revision of each surviving row, which is
|
|
31
|
+
* what a delta read compares against a client cursor.
|
|
32
|
+
*/
|
|
33
|
+
export declare function projectCompactHistory(history: SessionHistory, sourceRevs?: readonly number[]): CompactConversationHistory;
|
|
26
34
|
export declare function estimateCompactHistoryBytes(history: CompactConversationHistory | null): number;
|
|
27
35
|
export declare function projectSubagentHistory(history: SessionHistory | null, subagentId: string): SubagentConversationHistory;
|
|
@@ -26,6 +26,7 @@ function copyEvent(event, elapsed) {
|
|
|
26
26
|
function createCompactState() {
|
|
27
27
|
return {
|
|
28
28
|
events: [],
|
|
29
|
+
eventRevs: [],
|
|
29
30
|
summaries: new Map(),
|
|
30
31
|
summaryOrder: [],
|
|
31
32
|
previousMs: null,
|
|
@@ -121,10 +122,11 @@ function consumeChildEvent(state, event) {
|
|
|
121
122
|
}
|
|
122
123
|
markDetail(summary, event);
|
|
123
124
|
}
|
|
124
|
-
function pushCompactEvent(state, event, elapsed) {
|
|
125
|
+
function pushCompactEvent(state, event, elapsed, rev) {
|
|
125
126
|
state.events.push(copyEvent(event, elapsed));
|
|
127
|
+
state.eventRevs.push(rev);
|
|
126
128
|
}
|
|
127
|
-
function consumeCompactEvent(state, event) {
|
|
129
|
+
function consumeCompactEvent(state, event, rev = 0) {
|
|
128
130
|
const elapsed = elapsedMs(state.previousMs, event.ts);
|
|
129
131
|
state.previousMs = nextPreviousMs(event.ts);
|
|
130
132
|
if (event.type === 'user')
|
|
@@ -133,7 +135,7 @@ function consumeCompactEvent(state, event) {
|
|
|
133
135
|
if (event.subagentId && !isStructuralSpawnTool(event))
|
|
134
136
|
consumeChildEvent(state, event);
|
|
135
137
|
if (keepCompactEvent(state, event))
|
|
136
|
-
pushCompactEvent(state, event, elapsed);
|
|
138
|
+
pushCompactEvent(state, event, elapsed, rev);
|
|
137
139
|
}
|
|
138
140
|
function summarize(state) {
|
|
139
141
|
return state.summaryOrder.map((id) => {
|
|
@@ -157,16 +159,21 @@ function sealReportedEnds(state, history) {
|
|
|
157
159
|
summary.structurallyOpen = false;
|
|
158
160
|
}
|
|
159
161
|
}
|
|
160
|
-
|
|
162
|
+
/**
|
|
163
|
+
* Fold a parsed history into the compact read model. `sourceRevs` is positional against
|
|
164
|
+
* `history.events`; supply it and the result carries the revision of each surviving row, which is
|
|
165
|
+
* what a delta read compares against a client cursor.
|
|
166
|
+
*/
|
|
167
|
+
export function projectCompactHistory(history, sourceRevs) {
|
|
161
168
|
const state = createCompactState();
|
|
162
|
-
|
|
163
|
-
consumeCompactEvent(state, event);
|
|
169
|
+
history.events.forEach((event, index) => consumeCompactEvent(state, event, sourceRevs?.[index] ?? 0));
|
|
164
170
|
sealReportedEnds(state, history);
|
|
165
171
|
return {
|
|
166
172
|
sessionId: history.sessionId,
|
|
167
173
|
events: state.events,
|
|
168
174
|
committedSourceIds: history.committedSourceIds ?? [],
|
|
169
175
|
subagentSummaries: summarize(state),
|
|
176
|
+
...(sourceRevs ? { eventRevs: state.eventRevs } : {}),
|
|
170
177
|
};
|
|
171
178
|
}
|
|
172
179
|
export function estimateCompactHistoryBytes(history) {
|
|
@@ -2,11 +2,30 @@ import type { HistoryReadOptions, RawEvent, SessionHistory } from './conversatio
|
|
|
2
2
|
export declare class ConversationHistoryAccumulator {
|
|
3
3
|
private readonly sessionId;
|
|
4
4
|
private readonly state;
|
|
5
|
+
/** Byte offset of the first byte of the file NOT yet folded in. */
|
|
6
|
+
private cursor;
|
|
5
7
|
constructor(sessionId: string, options?: HistoryReadOptions);
|
|
8
|
+
/** Bytes of the source file already folded in — where a resumed read starts. */
|
|
9
|
+
get bytesConsumed(): number;
|
|
10
|
+
/** Monotonic revision of the folded model. Unchanged between two reads means nothing to redo. */
|
|
11
|
+
get revision(): number;
|
|
12
|
+
/** Rows folded so far. Zero means the file held nothing a transcript can show. */
|
|
13
|
+
get eventCount(): number;
|
|
14
|
+
/** @internal Advanced by the file fold; never rewound. */
|
|
15
|
+
advanceCursor(bytes: number): void;
|
|
6
16
|
consumeLine(line: string): void;
|
|
7
17
|
consumeRawEvent(ev: RawEvent, serializedLine?: string): void;
|
|
8
18
|
snapshot(): SessionHistory | null;
|
|
19
|
+
/** Per-row revisions, positionally aligned with `snapshot().events`. Live array — read only. */
|
|
20
|
+
eventRevisions(): readonly number[];
|
|
9
21
|
}
|
|
10
22
|
export declare function parseHistoryText(sessionId: string, raw: string, options?: HistoryReadOptions): Promise<SessionHistory | null>;
|
|
11
23
|
export declare function readHistoryAccumulator(sessionId: string, filePath: string, options?: HistoryReadOptions): Promise<ConversationHistoryAccumulator>;
|
|
24
|
+
/**
|
|
25
|
+
* Fold whatever the file has gained since this accumulator last read it. The file is append-only
|
|
26
|
+
* between rewrites, so a partially-read fold is a valid PREFIX state, not a spoiled one — resuming
|
|
27
|
+
* from the cursor is what turns a refresh from "re-parse the session" into "parse the new bytes".
|
|
28
|
+
* A rewrite (rewind / clear) is not resumable and is handled by the caller dropping the model.
|
|
29
|
+
*/
|
|
30
|
+
export declare function resumeHistoryAccumulator(accumulator: ConversationHistoryAccumulator, filePath: string): Promise<ConversationHistoryAccumulator>;
|
|
12
31
|
export declare function readHistoryStream(sessionId: string, filePath: string, options?: HistoryReadOptions): Promise<SessionHistory | null>;
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { createReadStream } from 'fs';
|
|
2
|
-
import {
|
|
3
|
-
import { debugToolWarningChars, isDebugToolOverWarningThreshold } from '../core/debug-mode.js';
|
|
2
|
+
import { isOverDebugToolWarningChars } from '../core/debug-mode.js';
|
|
4
3
|
function createParseState(options) {
|
|
5
4
|
return {
|
|
6
5
|
events: [],
|
|
6
|
+
revs: [],
|
|
7
|
+
revision: 0,
|
|
7
8
|
committedSourceIds: new Set(),
|
|
8
9
|
subagentEnds: new Map(),
|
|
9
10
|
interactionById: new Map(),
|
|
@@ -15,6 +16,23 @@ function createParseState(options) {
|
|
|
15
16
|
includeToolDebug: options.includeToolDebug !== false,
|
|
16
17
|
};
|
|
17
18
|
}
|
|
19
|
+
/** Append a row and stamp it with a fresh revision. Returns the row's index. */
|
|
20
|
+
function pushEvent(state, event) {
|
|
21
|
+
state.events.push(event);
|
|
22
|
+
state.revs.push(++state.revision);
|
|
23
|
+
return state.events.length - 1;
|
|
24
|
+
}
|
|
25
|
+
/** Re-stamp a row that an already-folded line reached back and changed. */
|
|
26
|
+
function touchEvent(state, index) {
|
|
27
|
+
if (index < 0 || index >= state.revs.length)
|
|
28
|
+
return;
|
|
29
|
+
state.revs[index] = ++state.revision;
|
|
30
|
+
}
|
|
31
|
+
/** Record a change that belongs to the model as a whole rather than to one row
|
|
32
|
+
* (subagent ends, committed source ids) — the projection is derived, so it must re-run. */
|
|
33
|
+
function touchModel(state) {
|
|
34
|
+
state.revision += 1;
|
|
35
|
+
}
|
|
18
36
|
function isPrefixRelated(a, b) {
|
|
19
37
|
return a.startsWith(b) || b.startsWith(a);
|
|
20
38
|
}
|
|
@@ -54,9 +72,11 @@ function noteLargeToolResult(state, line) {
|
|
|
54
72
|
if (state.includeToolDebug || !line.startsWith('{"type":"debug-tool-result"'))
|
|
55
73
|
return false;
|
|
56
74
|
const ref = debugResultToolRef(line);
|
|
57
|
-
const
|
|
58
|
-
|
|
75
|
+
const index = ref ? state.toolByUseId.get(ref) : undefined;
|
|
76
|
+
const tool = index === undefined ? undefined : state.events[index];
|
|
77
|
+
if (tool && isOverDebugToolWarningChars(line.length)) {
|
|
59
78
|
tool.debug = { ...(tool.debug ?? {}), overCharacterThreshold: true };
|
|
79
|
+
touchEvent(state, index);
|
|
60
80
|
}
|
|
61
81
|
return true;
|
|
62
82
|
}
|
|
@@ -71,25 +91,32 @@ function consumeSubagentEnd(state, ev) {
|
|
|
71
91
|
if (state.subagentEnds.has(ev.subagentId))
|
|
72
92
|
return;
|
|
73
93
|
state.subagentEnds.set(ev.subagentId, ev.subagentEnded);
|
|
94
|
+
touchModel(state);
|
|
74
95
|
}
|
|
75
96
|
function consumeDebugPrompt(state, ev) {
|
|
76
|
-
if (
|
|
97
|
+
if (state.lastUser === null || ev.agentMessage === undefined)
|
|
77
98
|
return;
|
|
78
|
-
|
|
99
|
+
const user = state.events[state.lastUser];
|
|
100
|
+
user.debug = { ...(user.debug ?? {}), agentMessage: ev.agentMessage };
|
|
101
|
+
touchEvent(state, state.lastUser);
|
|
79
102
|
}
|
|
80
103
|
function consumeDebugToolResult(state, ev) {
|
|
81
|
-
const
|
|
82
|
-
if (
|
|
104
|
+
const index = ev.toolUseId ? state.toolByUseId.get(ev.toolUseId) : undefined;
|
|
105
|
+
if (index === undefined)
|
|
83
106
|
return;
|
|
107
|
+
const tool = state.events[index];
|
|
84
108
|
tool.debug = {
|
|
85
109
|
...(tool.debug ?? {}),
|
|
86
110
|
toolResult: { content: ev.text ?? '', isError: ev.isError === true },
|
|
87
111
|
};
|
|
112
|
+
touchEvent(state, index);
|
|
88
113
|
}
|
|
89
114
|
function pushUser(state, ev) {
|
|
90
115
|
state.turnIndex += 1;
|
|
91
|
-
if (ev.sourceId)
|
|
116
|
+
if (ev.sourceId) {
|
|
92
117
|
state.committedSourceIds.add(ev.sourceId);
|
|
118
|
+
touchModel(state);
|
|
119
|
+
}
|
|
93
120
|
const user = {
|
|
94
121
|
type: 'user',
|
|
95
122
|
text: ev.text ?? '',
|
|
@@ -100,12 +127,12 @@ function pushUser(state, ev) {
|
|
|
100
127
|
...(state.pendingEdit ? { edited: state.pendingEdit } : {}),
|
|
101
128
|
...(ev.agentMessage !== undefined ? { debug: { agentMessage: ev.agentMessage } } : {}),
|
|
102
129
|
};
|
|
103
|
-
state.
|
|
104
|
-
state.lastUser = user;
|
|
130
|
+
state.lastUser = pushEvent(state, user);
|
|
105
131
|
state.pendingEdit = null;
|
|
106
132
|
}
|
|
107
133
|
function canCollapseAssistant(state, ev) {
|
|
108
|
-
const
|
|
134
|
+
const index = state.events.length - 1;
|
|
135
|
+
const last = state.events[index];
|
|
109
136
|
const text = ev.text ?? '';
|
|
110
137
|
const hasAttachments = ev.attachments !== undefined;
|
|
111
138
|
const hasDecisions = ev.decisions !== undefined && ev.decisions.length > 0;
|
|
@@ -117,22 +144,24 @@ function canCollapseAssistant(state, ev) {
|
|
|
117
144
|
return null;
|
|
118
145
|
if (last.subagentId !== ev.subagentId || typeof last.text !== 'string')
|
|
119
146
|
return null;
|
|
120
|
-
return isPrefixRelated(last.text, text) ?
|
|
147
|
+
return isPrefixRelated(last.text, text) ? index : null;
|
|
121
148
|
}
|
|
122
149
|
function pushAssistant(state, ev) {
|
|
123
|
-
const
|
|
150
|
+
const collapseInto = canCollapseAssistant(state, ev);
|
|
124
151
|
const text = ev.text ?? '';
|
|
125
|
-
if (
|
|
152
|
+
if (collapseInto !== null) {
|
|
153
|
+
const existing = state.events[collapseInto];
|
|
126
154
|
if (text.length >= existing.text.length) {
|
|
127
155
|
existing.text = text;
|
|
128
156
|
existing.ts = ev.ts;
|
|
157
|
+
touchEvent(state, collapseInto);
|
|
129
158
|
}
|
|
130
159
|
return;
|
|
131
160
|
}
|
|
132
161
|
const decisions = ev.decisions?.length
|
|
133
162
|
? ev.decisions.map((decision) => ({ ...decision, actions: [] }))
|
|
134
163
|
: undefined;
|
|
135
|
-
state
|
|
164
|
+
const index = pushEvent(state, {
|
|
136
165
|
type: 'assistant',
|
|
137
166
|
text,
|
|
138
167
|
ts: ev.ts,
|
|
@@ -145,11 +174,14 @@ function pushAssistant(state, ev) {
|
|
|
145
174
|
...subagentFields(ev),
|
|
146
175
|
});
|
|
147
176
|
for (const decision of decisions ?? [])
|
|
148
|
-
state.decisionById.set(decision.id, decision);
|
|
177
|
+
state.decisionById.set(decision.id, { index, decision });
|
|
149
178
|
}
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
179
|
+
/** `chars` is the length of the JSON line this event was parsed from — see
|
|
180
|
+
* `isOverDebugToolWarningChars`. The verdict is stamped on DEBUG and plain reads alike: the fold
|
|
181
|
+
* is the only place that still holds the row's own bytes, so stamping here is what lets every
|
|
182
|
+
* reader downstream trust the flag instead of re-deriving it from the parsed input. */
|
|
183
|
+
function toolDebug(state, ev, chars) {
|
|
184
|
+
const warned = ev.fullInput !== undefined && isOverDebugToolWarningChars(chars);
|
|
153
185
|
if (!ev.toolUseId && !warned && (!state.includeToolDebug || ev.fullInput === undefined))
|
|
154
186
|
return undefined;
|
|
155
187
|
return {
|
|
@@ -158,8 +190,8 @@ function toolDebug(state, ev) {
|
|
|
158
190
|
...(warned ? { overCharacterThreshold: true } : {}),
|
|
159
191
|
};
|
|
160
192
|
}
|
|
161
|
-
function pushTool(state, ev) {
|
|
162
|
-
const debug = toolDebug(state, ev);
|
|
193
|
+
function pushTool(state, ev, chars) {
|
|
194
|
+
const debug = toolDebug(state, ev, chars);
|
|
163
195
|
const tool = {
|
|
164
196
|
type: 'tool',
|
|
165
197
|
toolName: ev.toolName ?? '',
|
|
@@ -171,9 +203,9 @@ function pushTool(state, ev) {
|
|
|
171
203
|
...(ev.subagentSpawns?.length ? { subagentSpawns: ev.subagentSpawns } : {}),
|
|
172
204
|
...subagentFields(ev),
|
|
173
205
|
};
|
|
174
|
-
state
|
|
206
|
+
const index = pushEvent(state, tool);
|
|
175
207
|
if (ev.toolUseId)
|
|
176
|
-
state.toolByUseId.set(ev.toolUseId,
|
|
208
|
+
state.toolByUseId.set(ev.toolUseId, index);
|
|
177
209
|
}
|
|
178
210
|
function mergeResolvedInteraction(prior, ev) {
|
|
179
211
|
prior.status = ev.status;
|
|
@@ -187,12 +219,13 @@ function mergeResolvedInteraction(prior, ev) {
|
|
|
187
219
|
}
|
|
188
220
|
function pushInteraction(state, ev) {
|
|
189
221
|
if (!ev.id) {
|
|
190
|
-
state
|
|
222
|
+
pushEvent(state, { type: 'interaction', subtype: ev.subtype, text: ev.text ?? '', ts: ev.ts, turnIndex: turnFor(state) });
|
|
191
223
|
return;
|
|
192
224
|
}
|
|
193
|
-
const
|
|
194
|
-
if (
|
|
195
|
-
mergeResolvedInteraction(
|
|
225
|
+
const priorIndex = state.interactionById.get(ev.id);
|
|
226
|
+
if (priorIndex !== undefined && ev.status && ev.status !== 'pending') {
|
|
227
|
+
mergeResolvedInteraction(state.events[priorIndex], ev);
|
|
228
|
+
touchEvent(state, priorIndex);
|
|
196
229
|
return;
|
|
197
230
|
}
|
|
198
231
|
const interaction = {
|
|
@@ -207,20 +240,20 @@ function pushInteraction(state, ev) {
|
|
|
207
240
|
ts: ev.ts,
|
|
208
241
|
turnIndex: turnFor(state),
|
|
209
242
|
};
|
|
210
|
-
state.
|
|
211
|
-
state.interactionById.set(ev.id, interaction);
|
|
243
|
+
state.interactionById.set(ev.id, pushEvent(state, interaction));
|
|
212
244
|
}
|
|
213
245
|
function consumeDecisionAction(state, ev) {
|
|
214
246
|
const target = ev.decisionId ? state.decisionById.get(ev.decisionId) : undefined;
|
|
215
247
|
if (!target || !ev.action)
|
|
216
248
|
return;
|
|
217
|
-
target.actions.push({
|
|
249
|
+
target.decision.actions.push({
|
|
218
250
|
action: ev.action,
|
|
219
251
|
...(ev.message !== undefined ? { message: ev.message } : {}),
|
|
220
252
|
ts: ev.ts,
|
|
221
253
|
});
|
|
254
|
+
touchEvent(state, target.index);
|
|
222
255
|
}
|
|
223
|
-
function consumeParsedEvent(state, ev) {
|
|
256
|
+
function consumeParsedEvent(state, ev, chars) {
|
|
224
257
|
if (ev.type === 'edit-marker')
|
|
225
258
|
return consumeEditMarker(state, ev);
|
|
226
259
|
if (ev.type === 'subagent-end')
|
|
@@ -236,7 +269,7 @@ function consumeParsedEvent(state, ev) {
|
|
|
236
269
|
if (ev.type === 'assistant')
|
|
237
270
|
return pushAssistant(state, ev);
|
|
238
271
|
if (ev.type === 'tool')
|
|
239
|
-
return pushTool(state, ev);
|
|
272
|
+
return pushTool(state, ev, chars);
|
|
240
273
|
pushInteraction(state, ev);
|
|
241
274
|
}
|
|
242
275
|
function finishHistory(sessionId, state) {
|
|
@@ -254,13 +287,92 @@ async function consumeHistoryIterable(accumulator, lines) {
|
|
|
254
287
|
accumulator.consumeLine(line);
|
|
255
288
|
return accumulator;
|
|
256
289
|
}
|
|
290
|
+
const NEWLINE = 0x0a;
|
|
291
|
+
const CARRIAGE_RETURN = 0x0d;
|
|
292
|
+
/**
|
|
293
|
+
* Fold a JSONL file into `accumulator`, starting at its byte cursor, and stop at the last COMPLETE
|
|
294
|
+
* line. Deliberately byte-level rather than `readline`:
|
|
295
|
+
*
|
|
296
|
+
* - The cursor has to be exact. It is what makes the next read resume instead of re-parsing the
|
|
297
|
+
* whole file, and `readline` reports lines, not byte offsets.
|
|
298
|
+
* - A concurrent append can be observed half-written (a multi-megabyte tool result is not one
|
|
299
|
+
* atomic write). `readline` would hand that fragment over as if it were a line and the cursor
|
|
300
|
+
* would step past it, losing the row for good. Stopping at the last newline leaves the fragment
|
|
301
|
+
* for the next read, which sees it whole.
|
|
302
|
+
*
|
|
303
|
+
* Splitting on the newline BYTE is safe for UTF-8: 0x0A cannot occur inside a multi-byte sequence.
|
|
304
|
+
*/
|
|
305
|
+
async function foldFileInto(accumulator, filePath, start) {
|
|
306
|
+
const stream = createReadStream(filePath, { start });
|
|
307
|
+
/** Pieces of a line whose newline has not arrived yet, kept UNJOINED until it does. Re-joining
|
|
308
|
+
* the tail onto every chunk instead is quadratic in the line's length, and a row here is a whole
|
|
309
|
+
* tool result: the largest in this store is 43MB, which that shape folds in 3.6 minutes against
|
|
310
|
+
* 1.8 seconds for one join at the end. Rows are joined once, when their newline lands. */
|
|
311
|
+
let pending = [];
|
|
312
|
+
let pendingBytes = 0;
|
|
313
|
+
let consumed = start;
|
|
314
|
+
try {
|
|
315
|
+
for await (const chunk of stream) {
|
|
316
|
+
let from = 0;
|
|
317
|
+
for (;;) {
|
|
318
|
+
// Only the new chunk is searched: everything before it has already been scanned.
|
|
319
|
+
const nl = chunk.indexOf(NEWLINE, from);
|
|
320
|
+
if (nl < 0)
|
|
321
|
+
break;
|
|
322
|
+
let line;
|
|
323
|
+
if (pendingBytes > 0) {
|
|
324
|
+
pending.push(chunk.subarray(from, nl));
|
|
325
|
+
line = Buffer.concat(pending, pendingBytes + (nl - from));
|
|
326
|
+
pending = [];
|
|
327
|
+
pendingBytes = 0;
|
|
328
|
+
}
|
|
329
|
+
else {
|
|
330
|
+
line = chunk.subarray(from, nl);
|
|
331
|
+
}
|
|
332
|
+
consumed += line.length + 1;
|
|
333
|
+
const end = line.length > 0 && line[line.length - 1] === CARRIAGE_RETURN
|
|
334
|
+
? line.length - 1 : line.length; // tolerate CRLF
|
|
335
|
+
accumulator.consumeLine(line.toString('utf8', 0, end));
|
|
336
|
+
from = nl + 1;
|
|
337
|
+
}
|
|
338
|
+
if (from < chunk.length) {
|
|
339
|
+
const tail = chunk.subarray(from);
|
|
340
|
+
pending.push(tail);
|
|
341
|
+
pendingBytes += tail.length;
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
finally {
|
|
346
|
+
accumulator.advanceCursor(consumed);
|
|
347
|
+
stream.destroy();
|
|
348
|
+
}
|
|
349
|
+
}
|
|
257
350
|
export class ConversationHistoryAccumulator {
|
|
258
351
|
sessionId;
|
|
259
352
|
state;
|
|
353
|
+
/** Byte offset of the first byte of the file NOT yet folded in. */
|
|
354
|
+
cursor = 0;
|
|
260
355
|
constructor(sessionId, options = {}) {
|
|
261
356
|
this.sessionId = sessionId;
|
|
262
357
|
this.state = createParseState(options);
|
|
263
358
|
}
|
|
359
|
+
/** Bytes of the source file already folded in — where a resumed read starts. */
|
|
360
|
+
get bytesConsumed() {
|
|
361
|
+
return this.cursor;
|
|
362
|
+
}
|
|
363
|
+
/** Monotonic revision of the folded model. Unchanged between two reads means nothing to redo. */
|
|
364
|
+
get revision() {
|
|
365
|
+
return this.state.revision;
|
|
366
|
+
}
|
|
367
|
+
/** Rows folded so far. Zero means the file held nothing a transcript can show. */
|
|
368
|
+
get eventCount() {
|
|
369
|
+
return this.state.events.length;
|
|
370
|
+
}
|
|
371
|
+
/** @internal Advanced by the file fold; never rewound. */
|
|
372
|
+
advanceCursor(bytes) {
|
|
373
|
+
if (bytes > this.cursor)
|
|
374
|
+
this.cursor = bytes;
|
|
375
|
+
}
|
|
264
376
|
consumeLine(line) {
|
|
265
377
|
if (!line.trim())
|
|
266
378
|
return;
|
|
@@ -268,7 +380,7 @@ export class ConversationHistoryAccumulator {
|
|
|
268
380
|
return;
|
|
269
381
|
const ev = parseRawEvent(line);
|
|
270
382
|
if (ev)
|
|
271
|
-
consumeParsedEvent(this.state, ev);
|
|
383
|
+
consumeParsedEvent(this.state, ev, line.length);
|
|
272
384
|
}
|
|
273
385
|
consumeRawEvent(ev, serializedLine) {
|
|
274
386
|
const line = serializedLine === undefined
|
|
@@ -276,11 +388,15 @@ export class ConversationHistoryAccumulator {
|
|
|
276
388
|
: serializedLine.endsWith('\n') ? serializedLine.slice(0, -1) : serializedLine;
|
|
277
389
|
if (noteLargeToolResult(this.state, line))
|
|
278
390
|
return;
|
|
279
|
-
consumeParsedEvent(this.state, ev);
|
|
391
|
+
consumeParsedEvent(this.state, ev, line.length);
|
|
280
392
|
}
|
|
281
393
|
snapshot() {
|
|
282
394
|
return finishHistory(this.sessionId, this.state);
|
|
283
395
|
}
|
|
396
|
+
/** Per-row revisions, positionally aligned with `snapshot().events`. Live array — read only. */
|
|
397
|
+
eventRevisions() {
|
|
398
|
+
return this.state.revs;
|
|
399
|
+
}
|
|
284
400
|
}
|
|
285
401
|
export async function parseHistoryText(sessionId, raw, options = {}) {
|
|
286
402
|
const accumulator = new ConversationHistoryAccumulator(sessionId, options);
|
|
@@ -288,16 +404,19 @@ export async function parseHistoryText(sessionId, raw, options = {}) {
|
|
|
288
404
|
return accumulator.snapshot();
|
|
289
405
|
}
|
|
290
406
|
export async function readHistoryAccumulator(sessionId, filePath, options = {}) {
|
|
291
|
-
const stream = createReadStream(filePath, { encoding: 'utf8' });
|
|
292
|
-
const lines = createInterface({ input: stream, crlfDelay: Infinity });
|
|
293
407
|
const accumulator = new ConversationHistoryAccumulator(sessionId, options);
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
408
|
+
await foldFileInto(accumulator, filePath, 0);
|
|
409
|
+
return accumulator;
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* Fold whatever the file has gained since this accumulator last read it. The file is append-only
|
|
413
|
+
* between rewrites, so a partially-read fold is a valid PREFIX state, not a spoiled one — resuming
|
|
414
|
+
* from the cursor is what turns a refresh from "re-parse the session" into "parse the new bytes".
|
|
415
|
+
* A rewrite (rewind / clear) is not resumable and is handled by the caller dropping the model.
|
|
416
|
+
*/
|
|
417
|
+
export async function resumeHistoryAccumulator(accumulator, filePath) {
|
|
418
|
+
await foldFileInto(accumulator, filePath, accumulator.bytesConsumed);
|
|
419
|
+
return accumulator;
|
|
301
420
|
}
|
|
302
421
|
export async function readHistoryStream(sessionId, filePath, options = {}) {
|
|
303
422
|
const accumulator = await readHistoryAccumulator(sessionId, filePath, options);
|