@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
|
@@ -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. */
|
|
@@ -20,11 +20,10 @@ 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';
|
|
25
|
+
import { isRebuildHeld, refuseTurnForRebuild } from '../domain/system/rebuild-hold.js';
|
|
26
26
|
const log = createLogger('agent-runner');
|
|
27
|
-
const TEMP_DIR = WORKSPACE_DIR;
|
|
28
27
|
export class AgentRunner {
|
|
29
28
|
_enqueue;
|
|
30
29
|
_track;
|
|
@@ -51,6 +50,21 @@ export class AgentRunner {
|
|
|
51
50
|
}
|
|
52
51
|
async _routeWithAdmission(ctx, mutationRelease, loadPlatformFiles) {
|
|
53
52
|
const { message, channel, adapter } = ctx;
|
|
53
|
+
// The supervisor is rebuilding or replacing this process (entry/daemon-notice.ts pushes the
|
|
54
|
+
// hold). A turn admitted now spawns a backend CLI whose stdout owner is about to be SIGTERMed:
|
|
55
|
+
// the CLI finishes, writes into a pipe nobody reads, and the turn hangs at "processing" forever
|
|
56
|
+
// (2026-09-21). Refused first, before anything is tracked, marked, leased or injected — a
|
|
57
|
+
// message folded into a turn that is about to die is lost just as thoroughly.
|
|
58
|
+
if (isRebuildHeld()) {
|
|
59
|
+
log.info(`Refusing turn on ${channel}: supervisor rebuild in progress`);
|
|
60
|
+
await refuseTurnForRebuild({
|
|
61
|
+
adapter,
|
|
62
|
+
channel,
|
|
63
|
+
text: ctx.userMessage || '',
|
|
64
|
+
interactive: message.senderId !== SYNTHETIC_CALLBACK_SENDER && !message.systemOrigin,
|
|
65
|
+
});
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
54
68
|
// DR-0016 top-level fallback: if this channel has a pending human-escalated subtask question,
|
|
55
69
|
// consume this message as the answer and short-circuit normal turn handling. Scope is narrow —
|
|
56
70
|
// the backstop is disarmed unless this exact channel is awaiting a human reply, and it is armed
|
|
@@ -120,9 +134,10 @@ export class AgentRunner {
|
|
|
120
134
|
...(ctx.message.systemOrigin ? { systemOrigin: ctx.message.systemOrigin } : {}),
|
|
121
135
|
messageId: ctx.message.ref.messageId,
|
|
122
136
|
attachments: ctx.message.webAttachments,
|
|
123
|
-
prepareBackendAttachments: async () => (await loadPlatformFiles()).map((file) => ({
|
|
137
|
+
prepareBackendAttachments: async () => (await loadPlatformFiles()).files.map((file) => ({
|
|
124
138
|
mimeType: file.mimetype,
|
|
125
139
|
path: file.localPath,
|
|
140
|
+
name: file.name,
|
|
126
141
|
})),
|
|
127
142
|
});
|
|
128
143
|
}
|
|
@@ -144,7 +159,7 @@ export class AgentRunner {
|
|
|
144
159
|
*/
|
|
145
160
|
async _executeReal(ctx, mutationRelease, loadPlatformFiles) {
|
|
146
161
|
const { message, channel, adapter, threadAnchorId, userMessage, agentMessage } = ctx;
|
|
147
|
-
const
|
|
162
|
+
const turnFiles = await collectTurnFiles(message, loadPlatformFiles);
|
|
148
163
|
const startTime = Date.now();
|
|
149
164
|
const backend = resolveBackendForChannel(channel);
|
|
150
165
|
let sessionId = await getSessionAsync(channel);
|
|
@@ -195,7 +210,7 @@ export class AgentRunner {
|
|
|
195
210
|
session: { sessionId, sessionName, backendSessionId, projectId, lease: sessionLease },
|
|
196
211
|
user: {
|
|
197
212
|
text: userMessage || '',
|
|
198
|
-
attachments: message.webAttachments,
|
|
213
|
+
attachments: mergeAttachments(message.webAttachments, turnFiles.platformAttachments),
|
|
199
214
|
...(message.systemOrigin ? { systemOrigin: message.systemOrigin } : {}),
|
|
200
215
|
},
|
|
201
216
|
ledger: { userMessageTs: message.ref.messageId },
|
|
@@ -213,7 +228,8 @@ export class AgentRunner {
|
|
|
213
228
|
},
|
|
214
229
|
channel,
|
|
215
230
|
userMessage: agentMessage,
|
|
216
|
-
files:
|
|
231
|
+
files: turnFiles.files,
|
|
232
|
+
failedFiles: turnFiles.failures,
|
|
217
233
|
trigger: 'user',
|
|
218
234
|
browserCdpEndpoint: browser.cdpEndpoint,
|
|
219
235
|
commissionMode: !!sessionCommissionId,
|
|
@@ -230,6 +246,11 @@ export class AgentRunner {
|
|
|
230
246
|
}
|
|
231
247
|
export const agentRunner = new AgentRunner();
|
|
232
248
|
// --- Helpers ---
|
|
249
|
+
/** Web uploads and platform downloads share one attachment list on the user's transcript row. */
|
|
250
|
+
function mergeAttachments(web, platform) {
|
|
251
|
+
const merged = [...(web ?? []), ...(platform ?? [])];
|
|
252
|
+
return merged.length > 0 ? merged : undefined;
|
|
253
|
+
}
|
|
233
254
|
// Moved to transcript-sink.ts (the one transcript observer). Re-exported here so the existing
|
|
234
255
|
// agent-runner tests and importers keep their import path.
|
|
235
256
|
export { persistSessionContextUsage };
|
|
@@ -241,12 +262,12 @@ export { resolveDefaultAgent, resolveSessionName } from './turn/turn-prep.js';
|
|
|
241
262
|
function createPlatformFileLoader(ctx) {
|
|
242
263
|
let pending = null;
|
|
243
264
|
return () => {
|
|
244
|
-
pending ??= downloadFiles(ctx.message
|
|
265
|
+
pending ??= downloadFiles(ctx.message, ctx.hasFiles, ctx.adapter);
|
|
245
266
|
return pending;
|
|
246
267
|
};
|
|
247
268
|
}
|
|
248
|
-
async function downloadFiles(
|
|
249
|
-
if (!hasFiles || !files)
|
|
250
|
-
return [];
|
|
251
|
-
return downloadPlatformFiles(files, adapter,
|
|
269
|
+
async function downloadFiles(message, hasFiles, adapter) {
|
|
270
|
+
if (!hasFiles || !message.files)
|
|
271
|
+
return { files: [], failures: [] };
|
|
272
|
+
return downloadPlatformFiles(message.files, adapter, inboundAttachmentKey(message));
|
|
252
273
|
}
|
|
@@ -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
|
+
}
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import type { DownloadedFile } from '../platform/index.js';
|
|
2
|
+
import type { AttachmentFailure } from './routing/file-handler.js';
|
|
2
3
|
import { projectStore } from '../domain/projects/index.js';
|
|
3
4
|
import { loadCommissionDraftContext, loadCommissionPromptContext, type CommissionPromptContext } from '../domain/commissions/commission-context.js';
|
|
4
5
|
import type { RunRequest } from '../domain/runs/request.js';
|
|
6
|
+
import type { AgentSlotConfig } from '../core/types/thread-types.js';
|
|
5
7
|
/** The ids the caller has already resolved for this turn. Mirrors the plan's `prepareRequest(ids)`
|
|
6
8
|
* shape: everything else on {@link PrepareConversationRequestOptions} is per-surface turn input. */
|
|
7
9
|
export interface ConversationSessionIds {
|
|
@@ -20,6 +22,9 @@ export interface PrepareConversationRequestOptions {
|
|
|
20
22
|
/** The raw user message (without the default agent's directive). */
|
|
21
23
|
userMessage: string;
|
|
22
24
|
files: DownloadedFile[];
|
|
25
|
+
/** Attachments the platform refused to hand over; named in the prompt so the agent cannot
|
|
26
|
+
* answer as though the user had sent nothing. */
|
|
27
|
+
failedFiles?: AttachmentFailure[];
|
|
23
28
|
/** Execution trigger; defaults to 'user'. Scheduled session-target dispatch passes 'scheduled'. */
|
|
24
29
|
trigger?: string;
|
|
25
30
|
scheduleTaskId?: string | null;
|
|
@@ -45,16 +50,48 @@ export interface PreparedRequest {
|
|
|
45
50
|
* in history) of a Web UI direct session (`web:` channel — the only path where the user explicitly
|
|
46
51
|
* binds the session to a project at create time), and only for real user projects (the `general`
|
|
47
52
|
* umbrella carries no signal). Unknown/deleted project ids inject nothing rather than a dead path.
|
|
53
|
+
* An agent with `projectContext: false` opts out of the block entirely — "record your findings in
|
|
54
|
+
* the project" is operational noise in an environment built for something else.
|
|
48
55
|
*/
|
|
49
56
|
export declare function resolveConversationProject(args: {
|
|
50
57
|
channel: string;
|
|
51
58
|
projectId: string;
|
|
52
59
|
isFreshSession: boolean;
|
|
60
|
+
projectContext?: boolean;
|
|
53
61
|
store?: Pick<typeof projectStore, 'get'>;
|
|
54
62
|
}): {
|
|
55
63
|
id: string;
|
|
56
64
|
contextDir: string;
|
|
57
65
|
} | null;
|
|
66
|
+
/**
|
|
67
|
+
* The policy one conversation turn opens under: the shared direct-run policy, the surface's own
|
|
68
|
+
* background intent, and the execution-environment fields the agent template declares.
|
|
69
|
+
*
|
|
70
|
+
* Every environment default equals what {@link DIRECT_RUN_POLICY} already said, so an agent that
|
|
71
|
+
* declares none of them produces that constant field for field — which is why adding the fields
|
|
72
|
+
* changed no existing session. `skills` and `settingSources` stay `undefined` rather than being
|
|
73
|
+
* defaulted here: absent means "whatever the backend loads on its own", and only the agent that
|
|
74
|
+
* opts out has an opinion.
|
|
75
|
+
*/
|
|
76
|
+
export declare function conversationRunPolicy(agentConfig: AgentSlotConfig, opts: {
|
|
77
|
+
channel: string;
|
|
78
|
+
browserCdpEndpoint?: string | null;
|
|
79
|
+
}): RunRequest['policy'];
|
|
80
|
+
/**
|
|
81
|
+
* Which agent — which execution environment — a conversation turn opens under.
|
|
82
|
+
*
|
|
83
|
+
* The chain is the profile chain's twin: the session's own choice (what the composer set, or what
|
|
84
|
+
* `!agent` recorded on the session), then the channel's selection, then the global default, then
|
|
85
|
+
* `main`. `getDefaultAgent(channel)` already folds the middle two together.
|
|
86
|
+
*
|
|
87
|
+
* A candidate that no longer resolves is SKIPPED rather than fatal: an agent renamed or deleted
|
|
88
|
+
* since it was persisted must not kill every turn of the session that named it, exactly as an
|
|
89
|
+
* unknown channel profile falls back instead of throwing (see the run-config resolution below).
|
|
90
|
+
*/
|
|
91
|
+
export declare function resolveConversationAgent(candidates: ReadonlyArray<string | null | undefined>, resolve?: (name: string) => AgentSlotConfig | null): {
|
|
92
|
+
agentName: string;
|
|
93
|
+
agentConfig: AgentSlotConfig;
|
|
94
|
+
};
|
|
58
95
|
/** The delivery key for a session's current commission binding, or null outside the mode. Bound
|
|
59
96
|
* wins over drafting: finalize clears the draft, and the two are never both meaningful. */
|
|
60
97
|
export declare function commissionBindingKey(session: {
|