@cortex-agent/server 2026.9.14 → 2026.9.21
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/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-commission/.claude-plugin/plugin.json +2 -2
- package/defaults/plugins/cortex-commission/plugin.json +2 -2
- package/defaults/plugins/cortex-commission/skills/commission/SKILL.md +3 -3
- 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/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 +0 -6
- package/dist/agent-adapter/claude/adapter.js +0 -8
- package/dist/agent-adapter/claude/defaults.d.ts +10 -7
- package/dist/agent-adapter/claude/defaults.js +18 -16
- package/dist/agent-adapter/claude/hooks-builder.js +2 -2
- package/dist/agent-adapter/claude/spawn-args.d.ts +0 -3
- package/dist/agent-adapter/claude/spawn-args.js +20 -16
- 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/mcp-bridge-logic.d.ts +11 -2
- package/dist/agent-adapter/pi/mcp-bridge-logic.js +32 -1
- package/dist/agent-adapter/pi/mcp-bridge.js +16 -15
- package/dist/agent-adapter/pi/session-options.d.ts +0 -6
- package/dist/agent-adapter/pi/session-options.js +1 -8
- package/dist/agent-adapter/types.d.ts +1 -1
- package/dist/core/mcp-tool-gate.d.ts +3 -17
- package/dist/core/mcp-tool-gate.js +4 -19
- 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/settings-spec.d.ts +22 -1
- package/dist/core/settings-spec.js +33 -2
- package/dist/core/types/agent-types.d.ts +3 -1
- package/dist/core/utils.d.ts +1 -1
- package/dist/core/utils.js +1 -1
- package/dist/domain/agents/config.d.ts +1 -1
- package/dist/domain/agents/config.js +1 -1
- package/dist/domain/agents/profile-switch.d.ts +1 -1
- package/dist/domain/agents/profile-switch.js +3 -5
- package/dist/domain/agents/subagent/runner.js +0 -1
- package/dist/domain/commissions/commission-draft.d.ts +58 -0
- package/dist/domain/commissions/commission-draft.js +87 -4
- package/dist/domain/commissions/commission-finalize.d.ts +8 -3
- package/dist/domain/commissions/commission-finalize.js +14 -0
- package/dist/domain/executions/registry.d.ts +1 -2
- package/dist/domain/executions/registry.js +0 -3
- 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/commission-tools.d.ts +12 -1
- package/dist/domain/mcp/tools/commission-tools.js +68 -14
- 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/projects/project-store.d.ts +1 -1
- package/dist/domain/projects/project-store.js +3 -3
- package/dist/domain/remote/client-hot-reload.js +3 -1
- package/dist/domain/remote/client-manager.js +105 -126
- package/dist/domain/remote/client-ssh-tunnel.d.ts +16 -5
- package/dist/domain/remote/client-ssh-tunnel.js +12 -5
- 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/builders.js +0 -1
- package/dist/domain/runs/compact.js +0 -1
- package/dist/domain/runs/engine-spec.d.ts +11 -4
- package/dist/domain/runs/engine-spec.js +7 -4
- package/dist/domain/runs/prompt.js +16 -10
- package/dist/domain/runs/request.d.ts +0 -1
- package/dist/domain/sessions/session-hooks.d.ts +5 -12
- package/dist/domain/sessions/session-hooks.js +6 -13
- package/dist/domain/sessions/session-lifecycle.d.ts +4 -4
- package/dist/domain/sessions/session-lifecycle.js +5 -6
- package/dist/domain/sessions/session-retention.d.ts +1 -3
- package/dist/domain/sessions/session-retention.js +9 -26
- package/dist/domain/sessions/session-use.d.ts +32 -0
- package/dist/domain/sessions/session-use.js +63 -0
- package/dist/domain/sessions/session.js +6 -5
- package/dist/domain/system/server-update-check.js +29 -1
- package/dist/domain/system/update-ui-state.d.ts +32 -0
- package/dist/domain/system/update-ui-state.js +63 -0
- 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 +2 -2
- package/dist/domain/tasks/system/task-cli.js +2 -2
- package/dist/domain/tasks/system/task-state.js +1 -1
- package/dist/domain/threads/runner.js +3 -2
- package/dist/domain/ui-service/app-router.d.ts +54 -3
- package/dist/domain/ui-service/app-router.js +12 -14
- package/dist/domain/ui-service/input-schemas.d.ts +49 -5
- package/dist/domain/ui-service/input-schemas.js +35 -9
- package/dist/domain/ui-service/mutate/platform-settings.js +1 -1
- package/dist/domain/ui-service/mutate/sessions.d.ts +17 -1
- package/dist/domain/ui-service/mutate/sessions.js +83 -3
- package/dist/domain/ui-service/mutate/system.d.ts +3 -1
- package/dist/domain/ui-service/mutate/system.js +13 -0
- 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 +1 -1
- 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 +1 -1
- package/dist/domain/ui-service/query/sessions.js +7 -0
- package/dist/domain/ui-service/query/system.d.ts +2 -1
- package/dist/domain/ui-service/query/system.js +4 -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 +3 -0
- package/dist/domain/ui-service/query-input-schemas.js +3 -0
- package/dist/domain/ui-service/trpc.js +1 -1
- package/dist/domain/ui-service/types.d.ts +175 -50
- package/dist/domain/ui-service/types.js +1 -1
- package/dist/domain/ui-service/ui-service.js +13 -33
- 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 +39 -29
- package/dist/entry/auth-login-cli.js +1 -1
- package/dist/entry/auth-login-terminal.js +1 -1
- 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 +5 -3
- package/dist/events/event-types.d.ts +5 -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 +4 -3
- package/dist/orchestration/agent-runner.js +25 -23
- package/dist/orchestration/attachments-store.d.ts +31 -0
- package/dist/orchestration/attachments-store.js +184 -0
- package/dist/orchestration/conversation-request.d.ts +30 -8
- package/dist/orchestration/conversation-request.js +62 -26
- package/dist/orchestration/edit-retry.js +2 -1
- package/dist/orchestration/interactions/ask-user-resume.js +2 -1
- package/dist/orchestration/interactions/plan-approvals.js +1 -1
- package/dist/orchestration/interactions/ui-update-prompt.d.ts +8 -0
- package/dist/orchestration/interactions/ui-update-prompt.js +47 -0
- package/dist/orchestration/outputs-store.d.ts +11 -0
- package/dist/orchestration/outputs-store.js +32 -6
- package/dist/orchestration/resume-dispatcher.js +2 -2
- 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 +240 -39
- package/dist/orchestration/session-compact.d.ts +3 -0
- package/dist/orchestration/session-compact.js +3 -2
- package/dist/orchestration/session-events.d.ts +6 -0
- package/dist/orchestration/session-events.js +5 -0
- 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 +11 -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 +21 -9
- 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/app-update.d.ts +11 -0
- package/dist/platform/ui-http/app-update.js +3 -0
- 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-ledger-repo.d.ts +10 -19
- package/dist/store/conversation-ledger-repo.js +143 -152
- 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.d.ts +34 -0
- package/dist/store/session-registry-import.js +182 -0
- package/dist/store/session-registry-journal.d.ts +107 -0
- package/dist/store/session-registry-journal.js +308 -19
- package/dist/store/session-registry-repo.d.ts +113 -28
- package/dist/store/session-registry-repo.js +288 -105
- package/dist/store/version-migrations.d.ts +29 -3
- package/dist/store/version-migrations.js +288 -24
- package/dist/store/waitpoint-repo.d.ts +108 -0
- package/dist/store/waitpoint-repo.js +94 -0
- package/package.json +2 -2
- package/web/dist/assets/index-CwwQNMpP.css +1 -0
- package/web/dist/assets/index-DLSfgq3o.js +444 -0
- package/web/dist/assets/{index-aHbOZSP6.js → index-DZTuqUO4.js} +1 -1
- package/web/dist/index.html +2 -2
- 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/dist/store/session-repo.d.ts +0 -65
- package/dist/store/session-repo.js +0 -184
- package/web/dist/assets/index-BuXbCsuz.js +0 -444
- package/web/dist/assets/index-CCPxQ94C.css +0 -1
- /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
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// @cortex-hook-version 2026.
|
|
2
|
+
// @cortex-hook-version 2026.9.15
|
|
3
3
|
// input: stdin JSON — Claude Code PreToolUse event payload
|
|
4
4
|
// output: stdout JSON — { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision, permissionDecisionReason }, systemMessage? }
|
|
5
5
|
// pos: PreToolUse hook — intercepts Edit/Write on size-capped context files and
|
|
6
6
|
// enforces their caps (limit table below; rules/status-md.md, rules/issues-md.md,
|
|
7
|
-
// rules/
|
|
7
|
+
// rules/agents-md.md): deny writes whose result exceeds the caps, unless the
|
|
8
8
|
// write shrinks an already-over-limit file (so cleanup stays possible); warn
|
|
9
9
|
// when approaching the cap. Guarded files:
|
|
10
10
|
// context/projects/<p>/STATUS.md — 80 lines / 6KB (state register)
|
|
11
11
|
// context/projects/<p>/ISSUES.md — 80 lines / 6KB (friction log)
|
|
12
|
-
//
|
|
13
|
-
// >>> If I am updated, be sure to update my header comment and the
|
|
12
|
+
// AGENTS.md anywhere under a context/ tree — 120 lines / 8KB (injected index)
|
|
13
|
+
// >>> If I am updated, be sure to update my header comment and the AGENTS.md in the same folder <<<
|
|
14
14
|
|
|
15
15
|
import { readFileSync, existsSync } from 'fs';
|
|
16
16
|
import { resolve, sep } from 'path';
|
|
@@ -61,16 +61,16 @@ const LIMIT_RULES = [
|
|
|
61
61
|
],
|
|
62
62
|
},
|
|
63
63
|
{
|
|
64
|
-
name: '
|
|
65
|
-
ruleFile: 'rules/
|
|
66
|
-
matches: (parts) => parts[parts.length - 1] === '
|
|
64
|
+
name: 'AGENTS.md',
|
|
65
|
+
ruleFile: 'rules/agents-md.md',
|
|
66
|
+
matches: (parts) => parts[parts.length - 1] === 'AGENTS.md' && parts.includes('context'),
|
|
67
67
|
maxLines: 120,
|
|
68
68
|
maxBytes: 8 * 1024,
|
|
69
69
|
warnLines: 90,
|
|
70
70
|
warnBytes: 6656,
|
|
71
71
|
capLabel: '120 lines AND 8KB',
|
|
72
72
|
trimAdvice: [
|
|
73
|
-
'
|
|
73
|
+
'AGENTS.md is a directory index loaded into every agent that works here: it answers "what is here, where to look", not the content itself. Trim before writing:',
|
|
74
74
|
'- collapse atomic directories (experiments/ knowledge/ patterns/ decisions/) to one line each pointing at their index.md,',
|
|
75
75
|
'- entry summaries already live in the atomic files and their auto-generated index.md — never duplicate them here,',
|
|
76
76
|
'- keep each index line to one sentence + pointer (<=200 chars).',
|
|
@@ -3,9 +3,9 @@
|
|
|
3
3
|
// input: stdin thread lifecycle payload, argv identity fallback
|
|
4
4
|
// output: HookResult for unresolved dispatch task state
|
|
5
5
|
// pos: Checks task status after a dispatched thread terminates
|
|
6
|
-
// >>> If I am updated, update my header comment and the parent folder's
|
|
6
|
+
// >>> If I am updated, update my header comment and the parent folder's AGENTS.md <<<
|
|
7
7
|
|
|
8
|
-
import { readFileSync, existsSync
|
|
8
|
+
import { readFileSync, existsSync } from 'fs';
|
|
9
9
|
import * as path from 'path';
|
|
10
10
|
import { homedir } from 'os';
|
|
11
11
|
|
|
@@ -16,8 +16,6 @@ const PROJECTS_DIR = process.env.CORTEX_PROJECTS_DIR
|
|
|
16
16
|
? path.resolve(process.env.CORTEX_PROJECTS_DIR)
|
|
17
17
|
: path.join(DATA_DIR, 'context', 'projects');
|
|
18
18
|
|
|
19
|
-
const CORTEX_RUN_DIR = path.join(DATA_DIR, 'tmp', 'cortex-run');
|
|
20
|
-
|
|
21
19
|
function noop() {
|
|
22
20
|
console.log(JSON.stringify({ insertAgent: false }));
|
|
23
21
|
}
|
|
@@ -79,35 +77,6 @@ function findTaskById(content, taskId) {
|
|
|
79
77
|
return task;
|
|
80
78
|
}
|
|
81
79
|
|
|
82
|
-
/** Find a cortex-run state file that references the given task. */
|
|
83
|
-
function findStateFileForTask(project, taskId) {
|
|
84
|
-
try {
|
|
85
|
-
if (!existsSync(CORTEX_RUN_DIR)) return null;
|
|
86
|
-
for (const entry of readdirSync(CORTEX_RUN_DIR, { withFileTypes: true })) {
|
|
87
|
-
if (!entry.isDirectory()) continue;
|
|
88
|
-
const statePath = path.join(CORTEX_RUN_DIR, entry.name, 'state.json');
|
|
89
|
-
if (!existsSync(statePath)) continue;
|
|
90
|
-
try {
|
|
91
|
-
const state = JSON.parse(readFileSync(statePath, 'utf8'));
|
|
92
|
-
if (state.task_project === project && state.task_id === taskId) {
|
|
93
|
-
return { runName: entry.name, ...state };
|
|
94
|
-
}
|
|
95
|
-
} catch {}
|
|
96
|
-
}
|
|
97
|
-
} catch {}
|
|
98
|
-
return null;
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
/** Check if a PID is still alive. */
|
|
102
|
-
function pidAlive(pid) {
|
|
103
|
-
try {
|
|
104
|
-
process.kill(pid, 0);
|
|
105
|
-
return true;
|
|
106
|
-
} catch {
|
|
107
|
-
return false;
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
|
|
111
80
|
async function main() {
|
|
112
81
|
let input = '';
|
|
113
82
|
for await (const chunk of process.stdin) input += chunk;
|
|
@@ -146,27 +115,20 @@ async function main() {
|
|
|
146
115
|
// Task is done — nothing to do.
|
|
147
116
|
if (task.status === 'done') { noop(); return; }
|
|
148
117
|
|
|
149
|
-
// Task is pending —
|
|
118
|
+
// Task is pending — something outside this thread owns its completion (a waitpoint signal, an
|
|
119
|
+
// operator). No recovery is automatic; just make the limbo visible to the agent that ran.
|
|
150
120
|
if (task.status === 'pending') {
|
|
151
|
-
const
|
|
152
|
-
if (
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
targetAgent,
|
|
163
|
-
prompt: [
|
|
164
|
-
`FYI: task [id: ${taskId}] in project "${project}" is still [pending] but cortex-run ${note}.`,
|
|
165
|
-
'Per current policy, pending→done recovery is not automatic. Check manually if needed.',
|
|
166
|
-
].join('\n'),
|
|
167
|
-
}));
|
|
168
|
-
return;
|
|
169
|
-
}
|
|
121
|
+
const targetAgent = ctx.previousAgent;
|
|
122
|
+
if (targetAgent) {
|
|
123
|
+
console.log(JSON.stringify({
|
|
124
|
+
insertAgent: false,
|
|
125
|
+
targetAgent,
|
|
126
|
+
prompt: [
|
|
127
|
+
`FYI: task [id: ${taskId}] in project "${project}" is still [pending] and the thread has finished.`,
|
|
128
|
+
'Per current policy, pending→done recovery is not automatic. Check manually if needed.',
|
|
129
|
+
].join('\n'),
|
|
130
|
+
}));
|
|
131
|
+
return;
|
|
170
132
|
}
|
|
171
133
|
noop();
|
|
172
134
|
return;
|
|
@@ -180,37 +142,17 @@ async function main() {
|
|
|
180
142
|
const targetAgent = ctx.previousAgent;
|
|
181
143
|
if (!targetAgent) { noop(); return; }
|
|
182
144
|
|
|
183
|
-
//
|
|
184
|
-
const stateFile = findStateFileForTask(project, taskId);
|
|
185
|
-
|
|
186
|
-
if (stateFile && stateFile.status === 'running') {
|
|
187
|
-
// cortex-run is running — this is a legitimate pending case.
|
|
188
|
-
// Engineer forgot to call cortex-task pending; auto-transition.
|
|
189
|
-
console.log(JSON.stringify({
|
|
190
|
-
insertAgent: false,
|
|
191
|
-
targetAgent,
|
|
192
|
-
prompt: [
|
|
193
|
-
`Auto-detected: task [id: ${taskId}] in project "${project}" is still claimed,`,
|
|
194
|
-
`but a cortex-run process "(${stateFile.runName})" is running for this task (PID ${stateFile.pid}).`,
|
|
195
|
-
`The engineer likely forgot to mark the task pending. Call:`,
|
|
196
|
-
` cortex-task pending --project ${project} --task-id ${taskId}`,
|
|
197
|
-
].join('\n'),
|
|
198
|
-
}));
|
|
199
|
-
return;
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
// No cortex-run state file — genuine orphan.
|
|
203
|
-
// Unclaim and prompt agent to resolve.
|
|
145
|
+
// The thread finished without transitioning the task — prompt the agent to resolve it.
|
|
204
146
|
console.log(JSON.stringify({
|
|
205
147
|
insertAgent: false,
|
|
206
148
|
targetAgent,
|
|
207
149
|
prompt: [
|
|
208
|
-
`Status check: task [id: ${taskId}] in project "${project}" is still marked [claimed] in TASKS.yaml, but the thread has finished
|
|
150
|
+
`Status check: task [id: ${taskId}] in project "${project}" is still marked [claimed] in TASKS.yaml, but the thread has finished.`,
|
|
209
151
|
'',
|
|
210
152
|
'Resolve the task status now — do not leave it in limbo:',
|
|
211
153
|
`- If done-when conditions are satisfied: cortex-task complete --project ${project} --task-id ${taskId} --note "<what you did>"`,
|
|
212
154
|
`- If blocked by external reasons: cortex-task block --project ${project} --task-id ${taskId} --reason "<reason>"`,
|
|
213
|
-
`- If
|
|
155
|
+
`- If something outside this thread still has to finish: cortex-task pending --project ${project} --task-id ${taskId}`,
|
|
214
156
|
`- If none of the above apply: cortex-task unclaim --project ${project} --task-id ${taskId}`,
|
|
215
157
|
'',
|
|
216
158
|
'After updating the task, commit the TASKS.yaml change.',
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// @cortex-hook-version 2026.
|
|
2
|
+
// @cortex-hook-version 2026.9.15-2
|
|
3
3
|
// input: stdin JSON — Claude Code PreToolUse event payload
|
|
4
4
|
// output: stdout JSON — { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision, permissionDecisionReason } }
|
|
5
5
|
// pos: PreToolUse hook — intercepts Edit/Write on **/TASKS.yaml, checks project lock
|
|
6
6
|
// allow when current process holds the lock; deny + helpful message otherwise
|
|
7
7
|
// Owner identity: process.env.CORTEX_EXECUTION_ID ?? manual:<user>:<pid>
|
|
8
|
-
// >>> If I am updated, be sure to update my header comment and the
|
|
8
|
+
// >>> If I am updated, be sure to update my header comment and the AGENTS.md in the same folder <<<
|
|
9
9
|
|
|
10
10
|
import { readFileSync, existsSync } from 'fs';
|
|
11
11
|
import { basename, resolve } from 'path';
|
|
@@ -17,6 +17,8 @@ export interface SendAgentFileArgs {
|
|
|
17
17
|
fileName?: string;
|
|
18
18
|
/** Optional caption shown alongside the file card. */
|
|
19
19
|
caption?: string;
|
|
20
|
+
/** Name of a connected cortex-client; the path is then read on THAT device, not on the server. */
|
|
21
|
+
device?: string;
|
|
20
22
|
}
|
|
21
23
|
export interface SendAgentFileDeps {
|
|
22
24
|
copyIntoOutputs?: (a: {
|
|
@@ -24,6 +26,13 @@ export interface SendAgentFileDeps {
|
|
|
24
26
|
filePath: string;
|
|
25
27
|
fileName?: string;
|
|
26
28
|
}) => Promise<StoredOutput>;
|
|
29
|
+
/** Injectable twin of `copyIntoOutputs` for the remote path. */
|
|
30
|
+
fetchIntoOutputs?: (a: {
|
|
31
|
+
sessionId: string;
|
|
32
|
+
device: string;
|
|
33
|
+
filePath: string;
|
|
34
|
+
fileName?: string;
|
|
35
|
+
}) => Promise<StoredOutput>;
|
|
27
36
|
appendAssistant?: (sessionId: string, opts: {
|
|
28
37
|
text: string;
|
|
29
38
|
ts?: string;
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import * as path from 'path';
|
|
2
2
|
import { conversationHistory } from '../store/conversation-history-repo.js';
|
|
3
3
|
import { publishSessionMessage } from './session-events.js';
|
|
4
|
-
import { copyFileIntoOutputs } from './outputs-store.js';
|
|
4
|
+
import { copyFileIntoOutputs, receiveIntoOutputs } from './outputs-store.js';
|
|
5
|
+
import { fetchRemoteFile, prepareRemoteFetch } from '../domain/remote/device-file.js';
|
|
5
6
|
export { copyFileIntoOutputs };
|
|
6
7
|
/** Minimal extension → MIME map for the common file kinds an agent shares. Anything unknown falls
|
|
7
8
|
* back to application/octet-stream (still downloadable, just no inline preview). */
|
|
@@ -28,6 +29,19 @@ export function classifyAttachment(mimeType) {
|
|
|
28
29
|
return 'video';
|
|
29
30
|
return 'file';
|
|
30
31
|
}
|
|
32
|
+
/** Nothing the chat can usefully show is this big, and the cap is what stops one `send_file` from
|
|
33
|
+
* filling the disk with a transfer nobody can cancel. */
|
|
34
|
+
const MAX_REMOTE_FILE_BYTES = 200 * 1024 * 1024;
|
|
35
|
+
/** Stream a device's file straight into the session's outputs area. */
|
|
36
|
+
async function defaultFetchIntoOutputs(a) {
|
|
37
|
+
// Stat first: it is what rejects a bad path or an oversized file before anything is reserved on
|
|
38
|
+
// disk, and it supplies the default display name. The device derives that name with ITS own path
|
|
39
|
+
// rules — basename() here would mis-split a Windows path on a Linux server.
|
|
40
|
+
const stat = await prepareRemoteFetch({
|
|
41
|
+
device: a.device, filePath: a.filePath, maxBytes: MAX_REMOTE_FILE_BYTES,
|
|
42
|
+
});
|
|
43
|
+
return receiveIntoOutputs({ sessionId: a.sessionId, fileName: a.fileName || stat.name }, destPath => fetchRemoteFile({ device: a.device, filePath: a.filePath, destPath, stat }).then(() => { }));
|
|
44
|
+
}
|
|
31
45
|
/**
|
|
32
46
|
* Deliver a file into a web chat session as an agent-sent attachment (20a). Copies the file into the
|
|
33
47
|
* session's outputs area, records an assistant message carrying the attachment (persisted, so it is
|
|
@@ -37,10 +51,15 @@ export function classifyAttachment(mimeType) {
|
|
|
37
51
|
*/
|
|
38
52
|
export async function sendAgentFile(args, deps = {}) {
|
|
39
53
|
const copy = deps.copyIntoOutputs ?? copyFileIntoOutputs;
|
|
54
|
+
const fetchIn = deps.fetchIntoOutputs ?? defaultFetchIntoOutputs;
|
|
40
55
|
const append = deps.appendAssistant ?? ((sid, o) => conversationHistory.appendAssistant(sid, o));
|
|
41
56
|
const publish = deps.publish ?? publishSessionMessage;
|
|
42
57
|
const now = deps.now ?? (() => new Date().toISOString());
|
|
43
|
-
|
|
58
|
+
// Only the source of the bytes differs. Once the file is in the outputs area, a device's file is
|
|
59
|
+
// an ordinary attachment — same card, same download endpoint, same transcript row.
|
|
60
|
+
const { relPath, name, size } = args.device
|
|
61
|
+
? await fetchIn({ sessionId: args.sessionId, device: args.device, filePath: args.filePath, fileName: args.fileName })
|
|
62
|
+
: await copy({ sessionId: args.sessionId, filePath: args.filePath, fileName: args.fileName });
|
|
44
63
|
const mimeType = extToMime(name);
|
|
45
64
|
const meta = { name, path: relPath, size, mimeType, type: classifyAttachment(mimeType) };
|
|
46
65
|
const ts = now();
|
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import type { PlatformAdapter,
|
|
1
|
+
import type { PlatformAdapter, IncomingMessage } from '../platform/index.js';
|
|
2
2
|
import { persistSessionContextUsage, type SessionContextUsagePersistenceDeps } from './transcript-sink.js';
|
|
3
|
+
import { type InboundFiles } from './routing/file-handler.js';
|
|
3
4
|
import { type TurnMutationRelease } from './turn-mutation-lock.js';
|
|
4
5
|
type Enqueuer = (channel: string, fn: () => Promise<void>) => boolean;
|
|
5
6
|
type Tracker = (delta: number) => void;
|
|
6
|
-
type PlatformFileLoader = () => Promise<
|
|
7
|
+
type PlatformFileLoader = () => Promise<InboundFiles>;
|
|
7
8
|
type Executor = (ctx: AgentRunnerCtx, mutationRelease: TurnMutationRelease, loadPlatformFiles: PlatformFileLoader) => Promise<void>;
|
|
8
9
|
/** Attempt mid-turn injection; true ⇒ the message was delivered into the live turn and must NOT
|
|
9
10
|
* be queued. Injectable so the routing branch is testable without a live backend. */
|
|
@@ -43,7 +44,7 @@ export declare class AgentRunner {
|
|
|
43
44
|
* Resolve what a turn needs but is not part of it — the files, the session record (found or
|
|
44
45
|
* created) with its use lease, the browser the session opted into — and open the turn.
|
|
45
46
|
*
|
|
46
|
-
* `sessionId` here is the STABLE tracking id:
|
|
47
|
+
* `sessionId` here is the STABLE tracking id: the registry binds channel → track id (not the
|
|
47
48
|
* backend id), and everything downstream (publish / history / status / Destination) keys on it.
|
|
48
49
|
* The backend resume target is resolved separately. A channel with no bound session yet (fresh
|
|
49
50
|
* Slack/Feishu/etc.) mints + registers + binds a track id up front, unifying it with the web path
|
|
@@ -20,11 +20,9 @@ import { prepareConversationRequest } from './conversation-request.js';
|
|
|
20
20
|
import { openTurn, buildInjectDeps, recordHistory } from './turn/turn.js';
|
|
21
21
|
import { acquireSessionUseLease, acquireTurnBrowser, collectTurnFiles, releaseTurnBrowser, } from './turn/turn-prep.js';
|
|
22
22
|
import { tryConsume as tryHumanAnswerBackstop } from './human-answer-backstop.js';
|
|
23
|
-
import { downloadFiles as downloadPlatformFiles } from './routing/file-handler.js';
|
|
24
|
-
import { WORKSPACE_DIR } from '../core/utils.js';
|
|
23
|
+
import { downloadFiles as downloadPlatformFiles, inboundAttachmentKey, } from './routing/file-handler.js';
|
|
25
24
|
import { acquireTurnMutationLock } from './turn-mutation-lock.js';
|
|
26
25
|
const log = createLogger('agent-runner');
|
|
27
|
-
const TEMP_DIR = WORKSPACE_DIR;
|
|
28
26
|
export class AgentRunner {
|
|
29
27
|
_enqueue;
|
|
30
28
|
_track;
|
|
@@ -120,9 +118,10 @@ export class AgentRunner {
|
|
|
120
118
|
...(ctx.message.systemOrigin ? { systemOrigin: ctx.message.systemOrigin } : {}),
|
|
121
119
|
messageId: ctx.message.ref.messageId,
|
|
122
120
|
attachments: ctx.message.webAttachments,
|
|
123
|
-
prepareBackendAttachments: async () => (await loadPlatformFiles()).map((file) => ({
|
|
121
|
+
prepareBackendAttachments: async () => (await loadPlatformFiles()).files.map((file) => ({
|
|
124
122
|
mimeType: file.mimetype,
|
|
125
123
|
path: file.localPath,
|
|
124
|
+
name: file.name,
|
|
126
125
|
})),
|
|
127
126
|
});
|
|
128
127
|
}
|
|
@@ -136,7 +135,7 @@ export class AgentRunner {
|
|
|
136
135
|
* Resolve what a turn needs but is not part of it — the files, the session record (found or
|
|
137
136
|
* created) with its use lease, the browser the session opted into — and open the turn.
|
|
138
137
|
*
|
|
139
|
-
* `sessionId` here is the STABLE tracking id:
|
|
138
|
+
* `sessionId` here is the STABLE tracking id: the registry binds channel → track id (not the
|
|
140
139
|
* backend id), and everything downstream (publish / history / status / Destination) keys on it.
|
|
141
140
|
* The backend resume target is resolved separately. A channel with no bound session yet (fresh
|
|
142
141
|
* Slack/Feishu/etc.) mints + registers + binds a track id up front, unifying it with the web path
|
|
@@ -144,7 +143,7 @@ export class AgentRunner {
|
|
|
144
143
|
*/
|
|
145
144
|
async _executeReal(ctx, mutationRelease, loadPlatformFiles) {
|
|
146
145
|
const { message, channel, adapter, threadAnchorId, userMessage, agentMessage } = ctx;
|
|
147
|
-
const
|
|
146
|
+
const turnFiles = await collectTurnFiles(message, loadPlatformFiles);
|
|
148
147
|
const startTime = Date.now();
|
|
149
148
|
const backend = resolveBackendForChannel(channel);
|
|
150
149
|
let sessionId = await getSessionAsync(channel);
|
|
@@ -154,10 +153,9 @@ export class AgentRunner {
|
|
|
154
153
|
let sessionLease = null;
|
|
155
154
|
/** Opt-in browser access, read off the session record (plan/embedded-browser.md §17). */
|
|
156
155
|
let sessionBrowser = null;
|
|
157
|
-
/** Set
|
|
158
|
-
* is
|
|
159
|
-
|
|
160
|
-
/** Set once a contract has landed. Either field means the session is in commission mode. */
|
|
156
|
+
/** Set once a contract has landed — the state that loads the commission skill (DR-0037 v4).
|
|
157
|
+
* Drafting is not tracked here: the drill needs no plugin, and the [Commission] block reads the
|
|
158
|
+
* session record itself (see resolveConversationCommission). */
|
|
161
159
|
let sessionCommissionId = null;
|
|
162
160
|
if (sessionId) {
|
|
163
161
|
sessionLease = await acquireSessionUseLease(sessionId);
|
|
@@ -167,11 +165,10 @@ export class AgentRunner {
|
|
|
167
165
|
backendSessionId = effectiveBackendSessionId(sessionLease.session);
|
|
168
166
|
projectId = sessionLease.session.projectId ?? 'general';
|
|
169
167
|
sessionBrowser = sessionLease.session.browser ?? null;
|
|
170
|
-
// settings.commissionEnabled is the global switch for the feature
|
|
171
|
-
//
|
|
172
|
-
//
|
|
168
|
+
// settings.commissionEnabled is the global switch for the feature. With it off, a session
|
|
169
|
+
// that was bound while it was on reverts to an ordinary session: no commission skill, no
|
|
170
|
+
// contract block, and the commission tools refuse.
|
|
173
171
|
const commissionOn = getSettings().commissionEnabled;
|
|
174
|
-
sessionCommissionDraft = commissionOn ? sessionLease.session.commissionDraft ?? null : null;
|
|
175
172
|
sessionCommissionId = commissionOn ? sessionLease.session.commissionId ?? null : null;
|
|
176
173
|
}
|
|
177
174
|
else {
|
|
@@ -197,7 +194,7 @@ export class AgentRunner {
|
|
|
197
194
|
session: { sessionId, sessionName, backendSessionId, projectId, lease: sessionLease },
|
|
198
195
|
user: {
|
|
199
196
|
text: userMessage || '',
|
|
200
|
-
attachments: message.webAttachments,
|
|
197
|
+
attachments: mergeAttachments(message.webAttachments, turnFiles.platformAttachments),
|
|
201
198
|
...(message.systemOrigin ? { systemOrigin: message.systemOrigin } : {}),
|
|
202
199
|
},
|
|
203
200
|
ledger: { userMessageTs: message.ref.messageId },
|
|
@@ -215,11 +212,11 @@ export class AgentRunner {
|
|
|
215
212
|
},
|
|
216
213
|
channel,
|
|
217
214
|
userMessage: agentMessage,
|
|
218
|
-
files:
|
|
215
|
+
files: turnFiles.files,
|
|
216
|
+
failedFiles: turnFiles.failures,
|
|
219
217
|
trigger: 'user',
|
|
220
218
|
browserCdpEndpoint: browser.cdpEndpoint,
|
|
221
|
-
|
|
222
|
-
commissionMode: !!(sessionCommissionDraft || sessionCommissionId),
|
|
219
|
+
commissionMode: !!sessionCommissionId,
|
|
223
220
|
onPromptBuilt: debugEnabled ? (prompt) => {
|
|
224
221
|
recordHistory(conversationHistory.appendUserPrompt(trackSessionId, { agentMessage: prompt }), () => publishSessionDebugUpdated({ sessionId: trackSessionId, channel }));
|
|
225
222
|
} : null,
|
|
@@ -233,6 +230,11 @@ export class AgentRunner {
|
|
|
233
230
|
}
|
|
234
231
|
export const agentRunner = new AgentRunner();
|
|
235
232
|
// --- Helpers ---
|
|
233
|
+
/** Web uploads and platform downloads share one attachment list on the user's transcript row. */
|
|
234
|
+
function mergeAttachments(web, platform) {
|
|
235
|
+
const merged = [...(web ?? []), ...(platform ?? [])];
|
|
236
|
+
return merged.length > 0 ? merged : undefined;
|
|
237
|
+
}
|
|
236
238
|
// Moved to transcript-sink.ts (the one transcript observer). Re-exported here so the existing
|
|
237
239
|
// agent-runner tests and importers keep their import path.
|
|
238
240
|
export { persistSessionContextUsage };
|
|
@@ -244,12 +246,12 @@ export { resolveDefaultAgent, resolveSessionName } from './turn/turn-prep.js';
|
|
|
244
246
|
function createPlatformFileLoader(ctx) {
|
|
245
247
|
let pending = null;
|
|
246
248
|
return () => {
|
|
247
|
-
pending ??= downloadFiles(ctx.message
|
|
249
|
+
pending ??= downloadFiles(ctx.message, ctx.hasFiles, ctx.adapter);
|
|
248
250
|
return pending;
|
|
249
251
|
};
|
|
250
252
|
}
|
|
251
|
-
async function downloadFiles(
|
|
252
|
-
if (!hasFiles || !files)
|
|
253
|
-
return [];
|
|
254
|
-
return downloadPlatformFiles(files, adapter,
|
|
253
|
+
async function downloadFiles(message, hasFiles, adapter) {
|
|
254
|
+
if (!hasFiles || !message.files)
|
|
255
|
+
return { files: [], failures: [] };
|
|
256
|
+
return downloadPlatformFiles(message.files, adapter, inboundAttachmentKey(message));
|
|
255
257
|
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { DownloadedFile } from '../platform/types.js';
|
|
2
|
+
import type { AttachmentMeta } from '../domain/ui-service/types.js';
|
|
3
|
+
/** Physical directory backing the UI-relative `workspace/attachments/` prefix. */
|
|
4
|
+
export declare const ATTACHMENTS_DIR: string;
|
|
5
|
+
export declare function inboundAttachmentDir(key: string): string;
|
|
6
|
+
export declare function prepareInboundAttachmentDir(key: string): Promise<string>;
|
|
7
|
+
/** The UI-relative `workspace/…` alias for a path inside the workspace, or null when it is outside
|
|
8
|
+
* (a TUI attachment is the user's own file, referenced where it already lives). */
|
|
9
|
+
export declare function workspaceRelPath(absPath: string): string | null;
|
|
10
|
+
/**
|
|
11
|
+
* Settle a freshly downloaded file: believe its bytes over its metadata, and store it under the
|
|
12
|
+
* name the user sent it as.
|
|
13
|
+
*
|
|
14
|
+
* Only files the adapter wrote into `ownedDir` are renamed — an adapter that hands back a
|
|
15
|
+
* reference to a file it does not own (the TUI passes the user's own path through) keeps its
|
|
16
|
+
* location, and only its mimetype is corrected.
|
|
17
|
+
*/
|
|
18
|
+
export declare function finalizeInboundFile(file: DownloadedFile, ownedDir: string): Promise<DownloadedFile>;
|
|
19
|
+
/**
|
|
20
|
+
* Delete inbound attachment directories older than `maxAgeDays`.
|
|
21
|
+
*
|
|
22
|
+
* Age, not liveness: an attachment is read during the turn it arrives on (the backend is handed a
|
|
23
|
+
* path, and it reads the file within that turn), so nothing that matters is still pending days
|
|
24
|
+
* later. Only the per-message directories this module creates are swept — `<sessionId>/` uploads
|
|
25
|
+
* from the web composer are the UI's to keep, since its file cards link to them for as long as the
|
|
26
|
+
* transcript lives.
|
|
27
|
+
*/
|
|
28
|
+
export declare function pruneInboundAttachments(maxAgeDays: number, now?: () => number): Promise<number>;
|
|
29
|
+
/** The transcript card for an inbound attachment, or null for a file stored outside the workspace
|
|
30
|
+
* (the UI serves `workspace/…` paths only, so a TUI passthrough has nothing to link to). */
|
|
31
|
+
export declare function inboundAttachmentMeta(file: DownloadedFile): Promise<AttachmentMeta | null>;
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
// input: a file a platform adapter has just written into a directory this module owns
|
|
2
|
+
// output: that file under `workspace/attachments/<inbound key>/`, named after what the user sent
|
|
3
|
+
// it as, typed by what its bytes actually are — plus the age sweep that reclaims the space
|
|
4
|
+
// pos: orchestration — the inbound half of `outputs-store.ts` (which owns the agent-sent
|
|
5
|
+
// `workspace/outputs/` side) and the server-side twin of the web upload route, which
|
|
6
|
+
// stores composer uploads under `workspace/attachments/<sessionId>/`. Platform downloads
|
|
7
|
+
// used to land flat in WORKSPACE_DIR's root under their opaque platform id
|
|
8
|
+
// (`img_v3_02n4….png`), mixed in with agent scratch, never cleaned, and with the user's
|
|
9
|
+
// own filename dropped on the floor.
|
|
10
|
+
import * as path from 'path';
|
|
11
|
+
import { promises as fs } from 'fs';
|
|
12
|
+
import { WORKSPACE_DIR } from '../core/paths.js';
|
|
13
|
+
import { imageMimeExtension, sniffImageMime } from '../core/media-types.js';
|
|
14
|
+
import { createLogger } from '../core/log.js';
|
|
15
|
+
import { sanitizeDisplayFilename, sanitizeStorageFilename } from './outputs-store.js';
|
|
16
|
+
import { classifyAttachment, extToMime } from './agent-file-send.js';
|
|
17
|
+
const log = createLogger('attachments-store');
|
|
18
|
+
/** Physical directory backing the UI-relative `workspace/attachments/` prefix. */
|
|
19
|
+
export const ATTACHMENTS_DIR = path.join(WORKSPACE_DIR, 'attachments');
|
|
20
|
+
/** Bytes read to identify a file's real type. */
|
|
21
|
+
const SNIFF_BYTES = 16;
|
|
22
|
+
/** Marks the directories this module owns. A web composer upload lands under a bare `<sessionId>`
|
|
23
|
+
* in the same root and its files are linked from the transcript forever, so the age sweep must be
|
|
24
|
+
* able to tell the two apart by name alone. */
|
|
25
|
+
const INBOUND_PREFIX = 'in-';
|
|
26
|
+
/** One inbound message's own directory, so two files of the same name cannot collide across
|
|
27
|
+
* messages and the whole set can be reclaimed as a unit. */
|
|
28
|
+
function inboundDirName(key) {
|
|
29
|
+
const safe = key.replace(/[^A-Za-z0-9._-]/g, '-').replace(/^[.-]+/, '').slice(0, 120);
|
|
30
|
+
return `${INBOUND_PREFIX}${safe || 'message'}`;
|
|
31
|
+
}
|
|
32
|
+
export function inboundAttachmentDir(key) {
|
|
33
|
+
return path.join(ATTACHMENTS_DIR, inboundDirName(key));
|
|
34
|
+
}
|
|
35
|
+
export async function prepareInboundAttachmentDir(key) {
|
|
36
|
+
const dir = inboundAttachmentDir(key);
|
|
37
|
+
await fs.mkdir(dir, { recursive: true });
|
|
38
|
+
return dir;
|
|
39
|
+
}
|
|
40
|
+
/** The UI-relative `workspace/…` alias for a path inside the workspace, or null when it is outside
|
|
41
|
+
* (a TUI attachment is the user's own file, referenced where it already lives). */
|
|
42
|
+
export function workspaceRelPath(absPath) {
|
|
43
|
+
const root = path.resolve(WORKSPACE_DIR);
|
|
44
|
+
const resolved = path.resolve(absPath);
|
|
45
|
+
if (!resolved.startsWith(root + path.sep))
|
|
46
|
+
return null;
|
|
47
|
+
return `workspace/${path.relative(root, resolved).split(path.sep).join('/')}`;
|
|
48
|
+
}
|
|
49
|
+
/** Find an available filename in `dir`: on collision try `name_1`, `name_2`, … */
|
|
50
|
+
async function availablePath(dir, base) {
|
|
51
|
+
const extIdx = base.lastIndexOf('.');
|
|
52
|
+
const stem = extIdx > 0 ? base.slice(0, extIdx) : base;
|
|
53
|
+
const ext = extIdx > 0 ? base.slice(extIdx) : '';
|
|
54
|
+
let candidate = base;
|
|
55
|
+
let counter = 0;
|
|
56
|
+
for (;;) {
|
|
57
|
+
const p = path.join(dir, candidate);
|
|
58
|
+
try {
|
|
59
|
+
await fs.access(p);
|
|
60
|
+
counter++;
|
|
61
|
+
candidate = `${stem}_${counter}${ext}`;
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
return p;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/** The storage name for a download: the user's filename, ASCII-folded, re-extensioned when the
|
|
69
|
+
* bytes disagree with what it claimed to be. The Unicode original travels on `DownloadedFile.name`
|
|
70
|
+
* and reaches the model through the prompt and the UI through the attachment card. */
|
|
71
|
+
function storageName(displayName, sniffed) {
|
|
72
|
+
const base = sanitizeStorageFilename(displayName);
|
|
73
|
+
const wantExt = sniffed ? imageMimeExtension(sniffed) : null;
|
|
74
|
+
if (!wantExt)
|
|
75
|
+
return base;
|
|
76
|
+
const ext = path.extname(base).toLowerCase();
|
|
77
|
+
if (ext === wantExt || (wantExt === '.jpg' && ext === '.jpeg'))
|
|
78
|
+
return base;
|
|
79
|
+
const stem = ext ? base.slice(0, -ext.length) : base;
|
|
80
|
+
return `${stem || 'file'}${wantExt}`;
|
|
81
|
+
}
|
|
82
|
+
async function sniffFile(filePath) {
|
|
83
|
+
let handle;
|
|
84
|
+
try {
|
|
85
|
+
handle = await fs.open(filePath, 'r');
|
|
86
|
+
const buf = Buffer.alloc(SNIFF_BYTES);
|
|
87
|
+
const { bytesRead } = await handle.read(buf, 0, SNIFF_BYTES, 0);
|
|
88
|
+
return sniffImageMime(buf.subarray(0, bytesRead));
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
finally {
|
|
94
|
+
await handle?.close().catch(() => undefined);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Settle a freshly downloaded file: believe its bytes over its metadata, and store it under the
|
|
99
|
+
* name the user sent it as.
|
|
100
|
+
*
|
|
101
|
+
* Only files the adapter wrote into `ownedDir` are renamed — an adapter that hands back a
|
|
102
|
+
* reference to a file it does not own (the TUI passes the user's own path through) keeps its
|
|
103
|
+
* location, and only its mimetype is corrected.
|
|
104
|
+
*/
|
|
105
|
+
export async function finalizeInboundFile(file, ownedDir) {
|
|
106
|
+
const displayName = sanitizeDisplayFilename(file.name || path.basename(file.localPath));
|
|
107
|
+
const sniffed = await sniffFile(file.localPath);
|
|
108
|
+
// Bytes first, then what the platform said, then the name — Feishu hands a `file` message over
|
|
109
|
+
// with no mimetype at all, and an empty string reaches the UI as an undownloadable card.
|
|
110
|
+
const mimetype = sniffed ?? (file.mimetype || extToMime(displayName));
|
|
111
|
+
const owned = path.resolve(path.dirname(file.localPath)) === path.resolve(ownedDir);
|
|
112
|
+
if (!owned)
|
|
113
|
+
return { localPath: file.localPath, mimetype, name: displayName };
|
|
114
|
+
const target = await availablePath(ownedDir, storageName(displayName, sniffed));
|
|
115
|
+
if (path.resolve(target) !== path.resolve(file.localPath)) {
|
|
116
|
+
try {
|
|
117
|
+
await fs.rename(file.localPath, target);
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
log.warn(`could not rename ${file.localPath}: ${error.message}`);
|
|
121
|
+
return { localPath: file.localPath, mimetype, name: displayName };
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return { localPath: target, mimetype, name: displayName };
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Delete inbound attachment directories older than `maxAgeDays`.
|
|
128
|
+
*
|
|
129
|
+
* Age, not liveness: an attachment is read during the turn it arrives on (the backend is handed a
|
|
130
|
+
* path, and it reads the file within that turn), so nothing that matters is still pending days
|
|
131
|
+
* later. Only the per-message directories this module creates are swept — `<sessionId>/` uploads
|
|
132
|
+
* from the web composer are the UI's to keep, since its file cards link to them for as long as the
|
|
133
|
+
* transcript lives.
|
|
134
|
+
*/
|
|
135
|
+
export async function pruneInboundAttachments(maxAgeDays, now = Date.now) {
|
|
136
|
+
if (!(maxAgeDays > 0))
|
|
137
|
+
return 0;
|
|
138
|
+
const cutoff = now() - maxAgeDays * 24 * 60 * 60 * 1000;
|
|
139
|
+
let removed = 0;
|
|
140
|
+
let entries;
|
|
141
|
+
try {
|
|
142
|
+
entries = await fs.readdir(ATTACHMENTS_DIR);
|
|
143
|
+
}
|
|
144
|
+
catch {
|
|
145
|
+
return 0;
|
|
146
|
+
}
|
|
147
|
+
for (const entry of entries) {
|
|
148
|
+
if (!entry.startsWith(INBOUND_PREFIX))
|
|
149
|
+
continue;
|
|
150
|
+
const dir = path.join(ATTACHMENTS_DIR, entry);
|
|
151
|
+
try {
|
|
152
|
+
const stat = await fs.stat(dir);
|
|
153
|
+
if (!stat.isDirectory() || stat.mtimeMs >= cutoff)
|
|
154
|
+
continue;
|
|
155
|
+
await fs.rm(dir, { recursive: true, force: true });
|
|
156
|
+
removed++;
|
|
157
|
+
}
|
|
158
|
+
catch (error) {
|
|
159
|
+
log.warn(`could not prune ${dir}: ${error.message}`);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return removed;
|
|
163
|
+
}
|
|
164
|
+
/** The transcript card for an inbound attachment, or null for a file stored outside the workspace
|
|
165
|
+
* (the UI serves `workspace/…` paths only, so a TUI passthrough has nothing to link to). */
|
|
166
|
+
export async function inboundAttachmentMeta(file) {
|
|
167
|
+
const relPath = workspaceRelPath(file.localPath);
|
|
168
|
+
if (!relPath)
|
|
169
|
+
return null;
|
|
170
|
+
let size = 0;
|
|
171
|
+
try {
|
|
172
|
+
size = (await fs.stat(file.localPath)).size;
|
|
173
|
+
}
|
|
174
|
+
catch {
|
|
175
|
+
return null;
|
|
176
|
+
}
|
|
177
|
+
return {
|
|
178
|
+
name: file.name || path.basename(file.localPath),
|
|
179
|
+
path: relPath,
|
|
180
|
+
size,
|
|
181
|
+
mimeType: file.mimetype,
|
|
182
|
+
type: classifyAttachment(file.mimetype),
|
|
183
|
+
};
|
|
184
|
+
}
|