@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
|
@@ -6,6 +6,8 @@ export interface SlackToolDeps {
|
|
|
6
6
|
fallbackChannel: string | undefined;
|
|
7
7
|
branchMachine: string | undefined;
|
|
8
8
|
callbackSource: string | undefined;
|
|
9
|
+
/** Carried so file tools can reach the daemon to stage a remote device's file. */
|
|
10
|
+
ctx?: CortexToolContext;
|
|
9
11
|
}
|
|
10
12
|
/** Production deps for one session: a WebClient when the session carries a bot token. */
|
|
11
13
|
export declare function slackDepsFor(ctx: CortexToolContext): SlackToolDeps;
|
|
@@ -4,6 +4,7 @@ import * as fs from 'fs';
|
|
|
4
4
|
import * as path from 'path';
|
|
5
5
|
import { TokenBucketRateLimiter } from '../../../platform/utils/rate-limiter.js';
|
|
6
6
|
import { Icons } from '../../../core/icons.js';
|
|
7
|
+
import { withStagedRemoteFile } from './remote-file.js';
|
|
7
8
|
/** Production deps for one session: a WebClient when the session carries a bot token. */
|
|
8
9
|
export function slackDepsFor(ctx) {
|
|
9
10
|
return {
|
|
@@ -11,6 +12,7 @@ export function slackDepsFor(ctx) {
|
|
|
11
12
|
fallbackChannel: ctx.channel ?? undefined,
|
|
12
13
|
branchMachine: ctx.branchMachine ?? undefined,
|
|
13
14
|
callbackSource: ctx.callbackSource ?? undefined,
|
|
15
|
+
ctx,
|
|
14
16
|
};
|
|
15
17
|
}
|
|
16
18
|
/** Per-process rate limiter for the MCP server's Slack API calls.
|
|
@@ -98,30 +100,43 @@ export async function uploadFileToSlack(slack, { channel, filePath, fileName, ti
|
|
|
98
100
|
});
|
|
99
101
|
return { path: resolved, fileName: uploadName, size };
|
|
100
102
|
}
|
|
103
|
+
/** Tests construct deps without a context; only the remote path needs one, so it is demanded here
|
|
104
|
+
* rather than made mandatory for every Slack tool. */
|
|
105
|
+
function requireCtx(deps) {
|
|
106
|
+
if (!deps.ctx)
|
|
107
|
+
throw new Error('`device` is not available in this context');
|
|
108
|
+
return deps.ctx;
|
|
109
|
+
}
|
|
101
110
|
export function registerSlackTools(server, deps) {
|
|
102
|
-
server.tool('slack_send_file', 'Upload a
|
|
103
|
-
file_path: z.string().describe('Local
|
|
111
|
+
server.tool('slack_send_file', 'Upload a file to Slack. Use this when you need to share a file (image, log, data, etc.) with the user. The file may be on this server or, with `device`, on a connected remote device.', {
|
|
112
|
+
file_path: z.string().describe('File path to upload. Local path, or an absolute path on `device`.'),
|
|
104
113
|
file_name: z.string().optional().describe('Optional filename override shown in Slack'),
|
|
105
114
|
title: z.string().optional().describe('Optional file title shown in Slack'),
|
|
106
115
|
comment: z.string().optional().describe('Optional comment to accompany the file'),
|
|
107
|
-
|
|
116
|
+
device: z.string().optional().describe('Name of a connected remote device (as used by remote_bash). Omit for files on this server.'),
|
|
117
|
+
}, async ({ file_path, file_name, title, comment, device }) => {
|
|
108
118
|
try {
|
|
109
119
|
const channel = deps.fallbackChannel;
|
|
110
120
|
if (!channel)
|
|
111
121
|
throw new Error('No routing channel available');
|
|
112
122
|
if (!deps.slack)
|
|
113
123
|
throw new Error('Missing SLACK_BOT_TOKEN');
|
|
114
|
-
const
|
|
124
|
+
const upload = (filePath, name) => uploadFileToSlack(deps.slack, {
|
|
115
125
|
channel,
|
|
116
|
-
filePath
|
|
117
|
-
fileName:
|
|
126
|
+
filePath,
|
|
127
|
+
fileName: name,
|
|
118
128
|
title,
|
|
119
129
|
initialComment: comment || undefined,
|
|
120
130
|
});
|
|
131
|
+
// A device's file is fetched to disk first: the Slack SDK uploads from a path, so there is
|
|
132
|
+
// nothing to gain from streaming it anywhere else on the way.
|
|
133
|
+
const uploaded = device
|
|
134
|
+
? await withStagedRemoteFile(requireCtx(deps), device, file_path, staged => upload(staged.localPath, file_name || staged.name))
|
|
135
|
+
: await upload(file_path, file_name);
|
|
121
136
|
return {
|
|
122
137
|
content: [{
|
|
123
138
|
type: 'text',
|
|
124
|
-
text: `File uploaded: ${uploaded.fileName} (${uploaded.size} bytes)`,
|
|
139
|
+
text: `File uploaded${device ? ` from ${device}` : ''}: ${uploaded.fileName} (${uploaded.size} bytes)`,
|
|
125
140
|
}],
|
|
126
141
|
};
|
|
127
142
|
}
|
|
@@ -5,7 +5,8 @@ import * as crypto from 'crypto';
|
|
|
5
5
|
import { pathToFileURL } from 'url';
|
|
6
6
|
import { WORKSPACE_DIR } from '../../../core/utils.js';
|
|
7
7
|
import { requestLoopbackJson } from '../../../core/loopback-http.js';
|
|
8
|
-
import {
|
|
8
|
+
import { agentsMDContentBlocks } from './agents-md.js';
|
|
9
|
+
import { isAbsoluteFilePath } from './remote-file.js';
|
|
9
10
|
import { webhookAuthHeaders } from './context.js';
|
|
10
11
|
// Remote device commands are proxied through the daemon webhook: client-manager lives in the
|
|
11
12
|
// daemon and a tool must not reach into it directly.
|
|
@@ -15,15 +16,6 @@ async function proxySendCommand(ctx, device, action, params, timeout) {
|
|
|
15
16
|
throw new Error(body.error || 'Command failed');
|
|
16
17
|
return body.data;
|
|
17
18
|
}
|
|
18
|
-
/** Cross-platform absolute-path check (server runs on Linux but validates paths for Windows clients). */
|
|
19
|
-
function isAbsoluteFilePath(p) {
|
|
20
|
-
if (path.isAbsolute(p))
|
|
21
|
-
return true;
|
|
22
|
-
// Windows absolute: D:\, D:/, etc.
|
|
23
|
-
if (/^[A-Za-z]:[/\\]/.test(p))
|
|
24
|
-
return true;
|
|
25
|
-
return false;
|
|
26
|
-
}
|
|
27
19
|
// --- Tool result persistence ---
|
|
28
20
|
// When tool output exceeds a character threshold, save full output to a local
|
|
29
21
|
// file and return a pointer + preview. Prevents context window explosion while
|
|
@@ -191,7 +183,7 @@ export function registerTaskOpsTools(server, ctx) {
|
|
|
191
183
|
return { content: [{ type: 'text', text: 'file_path must be absolute' }], isError: true };
|
|
192
184
|
}
|
|
193
185
|
const result = await proxySendCommand(ctx, device, 'read', { file_path, offset, limit });
|
|
194
|
-
const cmdBlocks =
|
|
186
|
+
const cmdBlocks = agentsMDContentBlocks(device, result.cortexMDs, file_path);
|
|
195
187
|
// Image response path
|
|
196
188
|
if (result.image) {
|
|
197
189
|
const { data, mimeType, width, height, originalSize } = result.image;
|
|
@@ -264,7 +256,7 @@ export function registerTaskOpsTools(server, ctx) {
|
|
|
264
256
|
return { content: [{ type: 'text', text: 'file_path must be absolute' }], isError: true };
|
|
265
257
|
}
|
|
266
258
|
const result = await proxySendCommand(ctx, device, 'write', { file_path, content });
|
|
267
|
-
const cmdBlocks =
|
|
259
|
+
const cmdBlocks = agentsMDContentBlocks(device, result?.cortexMDs, file_path);
|
|
268
260
|
return {
|
|
269
261
|
content: [{ type: 'text', text: `File written: ${file_path}` }, ...cmdBlocks],
|
|
270
262
|
};
|
|
@@ -286,7 +278,7 @@ export function registerTaskOpsTools(server, ctx) {
|
|
|
286
278
|
return { content: [{ type: 'text', text: 'file_path must be absolute' }], isError: true };
|
|
287
279
|
}
|
|
288
280
|
const result = await proxySendCommand(ctx, device, 'edit', { file_path, old_string, new_string, replace_all: replace_all || false });
|
|
289
|
-
const cmdBlocks =
|
|
281
|
+
const cmdBlocks = agentsMDContentBlocks(device, result?.cortexMDs, file_path);
|
|
290
282
|
return {
|
|
291
283
|
content: [{ type: 'text', text: `File edited: ${file_path}` }, ...cmdBlocks],
|
|
292
284
|
};
|
|
@@ -2,27 +2,40 @@ import { z } from 'zod';
|
|
|
2
2
|
import * as fs from 'fs';
|
|
3
3
|
import * as path from 'path';
|
|
4
4
|
import { requestLoopbackJson } from '../../../core/loopback-http.js';
|
|
5
|
+
import { isAbsoluteFilePath } from './remote-file.js';
|
|
5
6
|
import { webhookAuthHeaders, webSessionId } from './context.js';
|
|
6
7
|
export function registerUiFileTools(server, ctx) {
|
|
7
|
-
server.tool('send_file', 'Send a file to the user in this chat. Use this whenever you want to share a file you produced — a report, plot, image, dataset, log, PDF, etc. The file appears as a downloadable card in the conversation (images preview inline). Pass a local path to a file you have written or that exists on disk.', {
|
|
8
|
-
file_path: z.string().describe('
|
|
8
|
+
server.tool('send_file', 'Send a file to the user in this chat. Use this whenever you want to share a file you produced — a report, plot, image, dataset, log, PDF, etc. The file appears as a downloadable card in the conversation (images preview inline). Pass a local path to a file you have written or that exists on disk, or set `device` to send a file that lives on a remote device instead.', {
|
|
9
|
+
file_path: z.string().describe('Path to the file to send. Local path (absolute, or relative to the working directory); with `device`, an absolute path on that device.'),
|
|
9
10
|
file_name: z.string().optional().describe('Optional filename override shown to the user.'),
|
|
10
11
|
caption: z.string().optional().describe('Optional short message shown alongside the file.'),
|
|
11
|
-
|
|
12
|
+
device: z.string().optional().describe('Name of a connected remote device (as used by remote_bash). The file is read there and streamed back. Omit for files on this server.'),
|
|
13
|
+
}, async ({ file_path, file_name, caption, device }) => {
|
|
12
14
|
try {
|
|
13
15
|
const sessionId = webSessionId(ctx);
|
|
14
16
|
if (!sessionId)
|
|
15
17
|
throw new Error('No web session in context — send_file is only usable inside a Web UI chat session');
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
if (
|
|
20
|
-
|
|
21
|
-
|
|
18
|
+
// With `device` the path belongs to another machine: it cannot be resolved or stat'ed here,
|
|
19
|
+
// and a relative path would be meaningless there. The daemon validates it on the device.
|
|
20
|
+
let resolved;
|
|
21
|
+
if (device) {
|
|
22
|
+
if (!isAbsoluteFilePath(file_path))
|
|
23
|
+
throw new Error('file_path must be absolute when `device` is set');
|
|
24
|
+
resolved = file_path;
|
|
25
|
+
}
|
|
26
|
+
else {
|
|
27
|
+
resolved = path.isAbsolute(file_path) ? file_path : path.resolve(process.cwd(), file_path);
|
|
28
|
+
if (!fs.existsSync(resolved))
|
|
29
|
+
throw new Error(`File not found: ${resolved}`);
|
|
30
|
+
if (!fs.statSync(resolved).isFile())
|
|
31
|
+
throw new Error(`Not a file: ${resolved}`);
|
|
32
|
+
}
|
|
33
|
+
const { body } = await requestLoopbackJson('POST', `${ctx.webhookBaseUrl}/webhook/ui-file`, { sessionId, filePath: resolved, fileName: file_name, caption, device }, webhookAuthHeaders(ctx));
|
|
22
34
|
if (!body.success)
|
|
23
35
|
throw new Error(body.error || 'send_file failed');
|
|
24
36
|
const meta = body.data;
|
|
25
|
-
|
|
37
|
+
const from = device ? ` from ${device}` : '';
|
|
38
|
+
return { content: [{ type: 'text', text: `Sent file to the user${from}: ${meta.name} (${meta.size} bytes)` }] };
|
|
26
39
|
}
|
|
27
40
|
catch (e) {
|
|
28
41
|
return { content: [{ type: 'text', text: `Failed to send file: ${e.message}` }], isError: true };
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { requestLoopbackJson } from '../../../core/loopback-http.js';
|
|
3
|
+
import { webhookAuthHeaders } from './context.js';
|
|
4
|
+
async function proxy(ctx, action, payload) {
|
|
5
|
+
const { body } = await requestLoopbackJson('POST', `${ctx.webhookBaseUrl}/webhook/waitpoint`, { action, sessionId: ctx.sessionId, channel: ctx.channel, threadId: ctx.threadId, project: ctx.taskProject || ctx.project, ...payload }, webhookAuthHeaders(ctx));
|
|
6
|
+
if (!body.success)
|
|
7
|
+
throw new Error(body.error || `waitpoint ${action} failed`);
|
|
8
|
+
return body.data;
|
|
9
|
+
}
|
|
10
|
+
function ok(payload) {
|
|
11
|
+
return { content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }] };
|
|
12
|
+
}
|
|
13
|
+
function fail(message) {
|
|
14
|
+
return { content: [{ type: 'text', text: message }], isError: true };
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* The three forms a signal can take, filled in with a real id and secret.
|
|
18
|
+
*
|
|
19
|
+
* `shell` is the one that matters for a remote machine: it needs no Cortex binary and no route
|
|
20
|
+
* back to the daemon — it drops a file the daemon comes and collects.
|
|
21
|
+
*/
|
|
22
|
+
function buildRecipe(id, secret, port, device) {
|
|
23
|
+
const env = `export CORTEX_SIGNAL_ID=${id} CORTEX_SIGNAL_SECRET=${secret}`;
|
|
24
|
+
const cli = `cortex-signal --exit-code $?`;
|
|
25
|
+
const curl = `curl -sS -XPOST http://127.0.0.1:${port}/webhook/signal `
|
|
26
|
+
+ `-H 'content-type: application/json' `
|
|
27
|
+
+ `-d '{"id":"${id}","secret":"${secret}","status":"ok","message":"done"}'`;
|
|
28
|
+
// Write-then-rename: a same-directory rename is atomic, so the drain never reads a half file.
|
|
29
|
+
const shell = [
|
|
30
|
+
`s=$?; d=~/.cortex/tmp/signals; mkdir -p "$d"`,
|
|
31
|
+
`printf '{"id":"${id}","secret":"${secret}","status":"%s","message":"exit=%s"}' `
|
|
32
|
+
+ `"$([ $s -eq 0 ] && echo ok || echo fail)" "$s" > "$d/$$.tmp" && mv "$d/$$.tmp" "$d/$$.json"`,
|
|
33
|
+
].join('\n');
|
|
34
|
+
// On a device the daemon cannot be reached over HTTP at all, so the file drop is the only
|
|
35
|
+
// form that works there; on this machine the CLI is shorter and reports failures immediately.
|
|
36
|
+
const attachToPid = `(while kill -0 <PID> 2>/dev/null; do sleep 5; done; `
|
|
37
|
+
+ `cortex-signal --status ok --message "pid <PID> exited") &`;
|
|
38
|
+
return { recommended: device ? 'shell' : 'cli', env, cli, curl, shell, attach_to_pid: attachToPid };
|
|
39
|
+
}
|
|
40
|
+
export function registerWaitpointTools(server, ctx) {
|
|
41
|
+
server.tool('wait_create', [
|
|
42
|
+
'Arm a waitpoint: a durable wake that anything outside Cortex can address. You get back an id,',
|
|
43
|
+
'a one-time secret and ready-to-paste lines; anything able to run one of them wakes this session',
|
|
44
|
+
'later, carrying a result.',
|
|
45
|
+
'',
|
|
46
|
+
'Shapes it takes:',
|
|
47
|
+
' a job that just finished python train.py; cortex-signal --exit-code $?',
|
|
48
|
+
' a job already running the reply\'s attach_to_pid line watches its pid',
|
|
49
|
+
' an alarm clock (sleep 3600; cortex-signal --message "an hour is up") &',
|
|
50
|
+
' a monitor max_signals > 1 — every report wakes you, until you cancel it',
|
|
51
|
+
' several jobs at once members + quorum — woken once, when the set is done',
|
|
52
|
+
'',
|
|
53
|
+
'Mechanism: Cortex launches nothing and watches nothing, so that callback exists only because',
|
|
54
|
+
'you put it somewhere. Arm the waitpoint before starting the job, so its line goes into the same',
|
|
55
|
+
'command; a waitpoint nobody signals just expires days later, having told you nothing.',
|
|
56
|
+
'',
|
|
57
|
+
'Then END YOUR TURN. Idle waiting is free and you never poll — when the signal lands this session',
|
|
58
|
+
'is woken with the result and the intent you recorded here.',
|
|
59
|
+
].join('\n'), {
|
|
60
|
+
label: z.string().describe('Short human name, e.g. "arm2 training". Appears in the wake message.'),
|
|
61
|
+
intent: z.string().describe('What you are waiting for and what you will do when woken, in your own words. You will read '
|
|
62
|
+
+ 'this hours later in a fresh turn with none of the current context, so write it for a stranger.'),
|
|
63
|
+
members: z.array(z.string()).optional().describe('Names of the jobs you expect to report, e.g. ["arm2","arm6","arm8"]. Each one signals with its own name.'),
|
|
64
|
+
quorum: z.union([z.number(), z.literal('all')]).optional().describe('How many terminal signals resolve this waitpoint. Defaults to "all" when members are given, else 1.'),
|
|
65
|
+
fail_fast: z.boolean().optional().describe('Wake on the first failure even if the quorum is unmet. Default true.'),
|
|
66
|
+
max_signals: z.number().optional().describe('How many times it may wake you before closing. Default 1: one job, one wake. Set it above 1 '
|
|
67
|
+
+ 'to keep the waitpoint open as a mailbox, so a job reporting every 30 minutes wakes you every '
|
|
68
|
+
+ 'time; cancel it yourself once you have what you need. A sender that should be recorded '
|
|
69
|
+
+ 'WITHOUT waking you uses `cortex-signal --status progress` instead.'),
|
|
70
|
+
expires_in_hours: z.number().optional().describe('Deadline. If nothing signals by then you are told so instead of waiting forever. Default 168h (7d), max 720h.'),
|
|
71
|
+
device: z.string().optional().describe('Name of the connected device the job runs on. Set this when the job is NOT on this machine: '
|
|
72
|
+
+ 'the daemon then collects signals from that device instead of expecting an HTTP call it cannot make.'),
|
|
73
|
+
}, async (args) => {
|
|
74
|
+
try {
|
|
75
|
+
const data = await proxy(ctx, 'create', {
|
|
76
|
+
label: args.label,
|
|
77
|
+
intent: args.intent,
|
|
78
|
+
quorum: { need: args.quorum, members: args.members },
|
|
79
|
+
failFast: args.fail_fast,
|
|
80
|
+
maxSignals: args.max_signals,
|
|
81
|
+
ttlMs: typeof args.expires_in_hours === 'number' ? args.expires_in_hours * 3600_000 : undefined,
|
|
82
|
+
device: args.device,
|
|
83
|
+
});
|
|
84
|
+
const port = Number(new URL(ctx.webhookBaseUrl).port || 3001);
|
|
85
|
+
const recipe = buildRecipe(data.id, data.secret, port, args.device ?? null);
|
|
86
|
+
return ok({
|
|
87
|
+
...data,
|
|
88
|
+
how_to_signal: recipe,
|
|
89
|
+
next: 'Nothing will signal this waitpoint unless you put one of the how_to_signal lines '
|
|
90
|
+
+ 'where the job runs it (start the job with it, or attach_to_pid if it is already '
|
|
91
|
+
+ 'running). Do that first, then end your turn — you will be woken.',
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
catch (e) {
|
|
95
|
+
return fail(`wait_create failed: ${e.message}`);
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
server.tool('wait_check', 'Inspect a waitpoint you armed: its state, which members have reported, and what they said. '
|
|
99
|
+
+ 'Pass an id, or omit it to list every waitpoint this session owns. Read-only — you do not need '
|
|
100
|
+
+ 'to poll this to be woken.', {
|
|
101
|
+
id: z.string().optional().describe('Waitpoint id (wp_…). Omit to list all of this session\'s waitpoints.'),
|
|
102
|
+
}, { readOnlyHint: true }, async (args) => {
|
|
103
|
+
try {
|
|
104
|
+
return ok(await proxy(ctx, 'check', { id: args.id }));
|
|
105
|
+
}
|
|
106
|
+
catch (e) {
|
|
107
|
+
return fail(`wait_check failed: ${e.message}`);
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
server.tool('wait_cancel', 'Disarm a waitpoint you no longer care about. Its secret stops working and you will not be woken. '
|
|
111
|
+
+ 'Use this when you gave up on the job or finished the work another way — an abandoned waitpoint '
|
|
112
|
+
+ 'otherwise wakes you days later about something nobody remembers.', {
|
|
113
|
+
id: z.string().describe('Waitpoint id (wp_…) to cancel.'),
|
|
114
|
+
}, async (args) => {
|
|
115
|
+
try {
|
|
116
|
+
return ok(await proxy(ctx, 'cancel', { id: args.id }));
|
|
117
|
+
}
|
|
118
|
+
catch (e) {
|
|
119
|
+
return fail(`wait_cancel failed: ${e.message}`);
|
|
120
|
+
}
|
|
121
|
+
});
|
|
122
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export interface AgentsMDEntry {
|
|
2
|
+
path: string;
|
|
3
|
+
content: string;
|
|
4
|
+
mtimeMs: number;
|
|
5
|
+
deviceId?: string;
|
|
6
|
+
}
|
|
7
|
+
export interface AgentsMDBlock {
|
|
8
|
+
type: 'text';
|
|
9
|
+
text: string;
|
|
10
|
+
}
|
|
11
|
+
export interface AgentsMDInjectorOptions {
|
|
12
|
+
sessionId?: string;
|
|
13
|
+
cacheDir?: string;
|
|
14
|
+
cacheFile?: string | null;
|
|
15
|
+
}
|
|
16
|
+
export declare class AgentsMDInjector {
|
|
17
|
+
private readonly memoryCache;
|
|
18
|
+
private readonly cacheFile;
|
|
19
|
+
constructor(options?: AgentsMDInjectorOptions);
|
|
20
|
+
private transact;
|
|
21
|
+
buildBlocks(device: string, entries: AgentsMDEntry[], markOnlyPaths?: Set<string>): AgentsMDBlock[];
|
|
22
|
+
private formatBlock;
|
|
23
|
+
}
|
|
24
|
+
export declare function getDefaultAgentsInjector(): AgentsMDInjector;
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import * as fs from 'fs';
|
|
2
2
|
import * as path from 'path';
|
|
3
3
|
import { WORKSPACE_DIR } from '../../core/utils.js';
|
|
4
|
+
// Directory name predates the AGENTS.md rename and is deliberately unchanged: it is shared
|
|
5
|
+
// with the local agents-md-injector hook, and renaming it would orphan every live session's
|
|
6
|
+
// dedup state at once, re-injecting every rule file already in context.
|
|
4
7
|
const DEFAULT_CACHE_DIR = path.join(WORKSPACE_DIR, 'cortexmd-cache');
|
|
5
8
|
const CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
|
6
9
|
const LOCK_WAIT_MS = 250;
|
|
@@ -91,7 +94,7 @@ function cacheKey(device, entry) {
|
|
|
91
94
|
const physicalDevice = entry.deviceId?.trim() || device;
|
|
92
95
|
return `${physicalDevice.toLowerCase()}:${entry.path}`;
|
|
93
96
|
}
|
|
94
|
-
export class
|
|
97
|
+
export class AgentsMDInjector {
|
|
95
98
|
memoryCache = new Map();
|
|
96
99
|
cacheFile;
|
|
97
100
|
constructor(options = {}) {
|
|
@@ -140,16 +143,16 @@ export class CortexMDInjector {
|
|
|
140
143
|
}
|
|
141
144
|
formatBlock(device, entry) {
|
|
142
145
|
return `<system-reminder>\n` +
|
|
143
|
-
`Auto-loaded
|
|
146
|
+
`Auto-loaded AGENTS.md from ${device}:${entry.path} ` +
|
|
144
147
|
`(ancestor of accessed path on remote device). ` +
|
|
145
148
|
`These instructions apply to files under this directory on that device.\n\n` +
|
|
146
149
|
entry.content +
|
|
147
150
|
`\n</system-reminder>`;
|
|
148
151
|
}
|
|
149
152
|
}
|
|
150
|
-
let
|
|
151
|
-
export function
|
|
152
|
-
if (!
|
|
153
|
-
|
|
154
|
-
return
|
|
153
|
+
let defaultAgentsInjector = null;
|
|
154
|
+
export function getDefaultAgentsInjector() {
|
|
155
|
+
if (!defaultAgentsInjector)
|
|
156
|
+
defaultAgentsInjector = new AgentsMDInjector();
|
|
157
|
+
return defaultAgentsInjector;
|
|
155
158
|
}
|
|
@@ -241,7 +241,7 @@ function skillSnapshotTarget(parent, selection, skill) {
|
|
|
241
241
|
function createSkillSnapshot(selection, skill, target) {
|
|
242
242
|
const tmp = projectionTemp(path.dirname(target), target);
|
|
243
243
|
try {
|
|
244
|
-
copyProjectedSkillTree(selection.root.real, skill.target, skill.tree, tmp);
|
|
244
|
+
copyProjectedSkillTree(selection.root.real, skill.target, skill.tree, tmp, { requireSourceSignature: true });
|
|
245
245
|
fs.renameSync(tmp, target);
|
|
246
246
|
return true;
|
|
247
247
|
}
|
|
@@ -1,13 +1,19 @@
|
|
|
1
1
|
export interface ProjectedSkillFile {
|
|
2
2
|
path: string;
|
|
3
|
-
|
|
3
|
+
/** Source identity (size, mtime, ctime, inode, mode) — what the copy re-validates against. */
|
|
4
|
+
signature: string;
|
|
5
|
+
/** Byte length of the source file; a materialized copy must match it. */
|
|
6
|
+
size: number;
|
|
4
7
|
mode: number;
|
|
5
8
|
}
|
|
6
9
|
export interface ProjectedSkillTree {
|
|
7
10
|
dirs: string[];
|
|
8
11
|
files: ProjectedSkillFile[];
|
|
12
|
+
/** Digest of the {dirs, files} descriptor (metadata only), used as the projection cache key. */
|
|
9
13
|
sha256: string;
|
|
10
14
|
}
|
|
11
15
|
export declare function buildProjectedSkillTree(packageRoot: string, skillRoot: string): ProjectedSkillTree;
|
|
12
|
-
export declare function copyProjectedSkillTree(packageRoot: string, skillRoot: string, tree: ProjectedSkillTree, targetRoot: string
|
|
16
|
+
export declare function copyProjectedSkillTree(packageRoot: string, skillRoot: string, tree: ProjectedSkillTree, targetRoot: string, opts?: {
|
|
17
|
+
requireSourceSignature?: boolean;
|
|
18
|
+
}): void;
|
|
13
19
|
export declare function validateProjectedSkillTree(targetRoot: string, expected: ProjectedSkillTree): void;
|
|
@@ -1,3 +1,13 @@
|
|
|
1
|
+
// input: validated portable skill directories
|
|
2
|
+
// output: snapshots, copies, and exact validators
|
|
3
|
+
// pos: Recursive portable skill projection helpers
|
|
4
|
+
//
|
|
5
|
+
// Change detection is stat-based on purpose: every projected file used to be read and sha256'd
|
|
6
|
+
// three times per spawn (build, copy, validate). The source-side guarantees — symlink containment,
|
|
7
|
+
// torn reads, "changed after validation" — hold on the identity of the inode (dev/ino) plus its
|
|
8
|
+
// stat signature (size, mtime, ctime, mode), which any content write or replacement moves. A
|
|
9
|
+
// materialized copy has its own inode and timestamps, so it is compared on path + byte length +
|
|
10
|
+
// mode + directory set. File bytes are never hashed.
|
|
1
11
|
import { createHash } from 'node:crypto';
|
|
2
12
|
import fs from 'node:fs';
|
|
3
13
|
import path from 'node:path';
|
|
@@ -20,25 +30,44 @@ function assertSameFile(expected, actual, filePath) {
|
|
|
20
30
|
throw new Error(`Skill file changed while being read: ${filePath}`);
|
|
21
31
|
}
|
|
22
32
|
}
|
|
23
|
-
|
|
33
|
+
/** Stable identity of a file without reading its bytes: any content write moves mtime/ctime,
|
|
34
|
+
* and any replacement moves the inode. */
|
|
35
|
+
function statSignature(stat) {
|
|
36
|
+
return `${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}:${stat.ino}:${stat.mode & 0o777}`;
|
|
37
|
+
}
|
|
38
|
+
const OPEN_FLAGS = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0);
|
|
39
|
+
/** Open a file through its realpath with O_NOFOLLOW and assert the inode did not change under us.
|
|
40
|
+
* Returns the open fd plus the validated stat — callers either stat it or read from it. */
|
|
41
|
+
function openStableFile(root, filePath) {
|
|
24
42
|
const resolved = safeRealpath(root, filePath);
|
|
25
|
-
const
|
|
26
|
-
const fd = fs.openSync(resolved, flags);
|
|
43
|
+
const fd = fs.openSync(resolved, OPEN_FLAGS);
|
|
27
44
|
try {
|
|
28
45
|
const opened = fs.fstatSync(fd);
|
|
29
46
|
assertRegularFile(opened, resolved);
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
47
|
+
// A symlink swapped in between realpath() and open() must be caught. lstat avoids a second
|
|
48
|
+
// realpath walk (the most expensive syscall here): for the regular file we expect, lstat and
|
|
49
|
+
// stat agree; a swapped-in symlink reports its own inode and mismatches.
|
|
50
|
+
assertSameFile(opened, fs.lstatSync(filePath), filePath);
|
|
51
|
+
return { fd, stat: fs.fstatSync(fd) };
|
|
34
52
|
}
|
|
35
|
-
|
|
53
|
+
catch (error) {
|
|
36
54
|
fs.closeSync(fd);
|
|
55
|
+
throw error;
|
|
37
56
|
}
|
|
38
57
|
}
|
|
39
58
|
function pushFile(packageRoot, files, filePath, relativePath) {
|
|
40
|
-
const
|
|
41
|
-
|
|
59
|
+
const { fd, stat } = openStableFile(packageRoot, filePath);
|
|
60
|
+
try {
|
|
61
|
+
files.push({
|
|
62
|
+
path: relativePath,
|
|
63
|
+
signature: statSignature(stat),
|
|
64
|
+
size: stat.size,
|
|
65
|
+
mode: stat.mode & 0o777,
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
finally {
|
|
69
|
+
fs.closeSync(fd);
|
|
70
|
+
}
|
|
42
71
|
}
|
|
43
72
|
function scanDirectory(packageRoot, logicalPath, relativePath, stack, dirs, files) {
|
|
44
73
|
const real = safeRealpath(packageRoot, logicalPath);
|
|
@@ -86,21 +115,40 @@ function ensureDir(directory) {
|
|
|
86
115
|
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
87
116
|
fs.chmodSync(directory, 0o700);
|
|
88
117
|
}
|
|
89
|
-
function copyFile(packageRoot, source, target, expected) {
|
|
90
|
-
const
|
|
91
|
-
|
|
92
|
-
|
|
118
|
+
function copyFile(packageRoot, source, target, expected, requireSourceSignature) {
|
|
119
|
+
const { fd, stat } = openStableFile(packageRoot, source);
|
|
120
|
+
try {
|
|
121
|
+
if (requireSourceSignature && statSignature(stat) !== expected.signature) {
|
|
122
|
+
throw new Error(`Skill file changed after validation: ${source}`);
|
|
123
|
+
}
|
|
124
|
+
// Byte length + mode are the descriptor-level contract for every copy; a same-length in-place
|
|
125
|
+
// rewrite is only distinguishable through the full signature, which the plugin-source copy
|
|
126
|
+
// enforces above. Copies taken from an already validated snapshot carry that snapshot's own
|
|
127
|
+
// timestamps, so they compare on shape.
|
|
128
|
+
if (stat.size !== expected.size || (stat.mode & 0o777) !== expected.mode) {
|
|
129
|
+
throw new Error(`Skill file changed after validation: ${source}`);
|
|
130
|
+
}
|
|
131
|
+
const bytes = fs.readFileSync(fd);
|
|
132
|
+
// No second read: the inode must be the one we opened, unchanged by the read itself.
|
|
133
|
+
const after = fs.fstatSync(fd);
|
|
134
|
+
assertSameFile(stat, after, source);
|
|
135
|
+
if (after.size !== expected.size || statSignature(after) !== statSignature(stat)) {
|
|
136
|
+
throw new Error(`Skill file changed while being read: ${source}`);
|
|
137
|
+
}
|
|
138
|
+
fs.writeFileSync(target, bytes, { mode: expected.mode });
|
|
139
|
+
fs.chmodSync(target, expected.mode);
|
|
140
|
+
}
|
|
141
|
+
finally {
|
|
142
|
+
fs.closeSync(fd);
|
|
93
143
|
}
|
|
94
|
-
fs.writeFileSync(target, file.bytes, { mode: expected.mode });
|
|
95
|
-
fs.chmodSync(target, expected.mode);
|
|
96
144
|
}
|
|
97
|
-
export function copyProjectedSkillTree(packageRoot, skillRoot, tree, targetRoot) {
|
|
145
|
+
export function copyProjectedSkillTree(packageRoot, skillRoot, tree, targetRoot, opts = {}) {
|
|
98
146
|
ensureDir(targetRoot);
|
|
99
147
|
for (const dir of tree.dirs)
|
|
100
148
|
ensureDir(path.join(targetRoot, dir));
|
|
101
149
|
for (const file of tree.files) {
|
|
102
150
|
ensureDir(path.dirname(path.join(targetRoot, file.path)));
|
|
103
|
-
copyFile(packageRoot, path.join(skillRoot, file.path), path.join(targetRoot, file.path), file);
|
|
151
|
+
copyFile(packageRoot, path.join(skillRoot, file.path), path.join(targetRoot, file.path), file, opts.requireSourceSignature === true);
|
|
104
152
|
}
|
|
105
153
|
}
|
|
106
154
|
function scanMaterializedDirectory(root, current, relativePath, dirs, files) {
|
|
@@ -128,12 +176,21 @@ function actualTree(root) {
|
|
|
128
176
|
files.sort((a, b) => a.path.localeCompare(b.path));
|
|
129
177
|
return { dirs, files, sha256: treeSha256(dirs, files) };
|
|
130
178
|
}
|
|
179
|
+
/** The parts of a tree a materialized copy can be compared on: the source's mtime/ctime/inode
|
|
180
|
+
* belong to the source, while a copy has its own. Path, byte length, mode and the directory set
|
|
181
|
+
* still catch a truncated, extra, missing or wrongly-permissioned projection. */
|
|
182
|
+
function materializedShape(tree) {
|
|
183
|
+
return JSON.stringify({
|
|
184
|
+
dirs: tree.dirs,
|
|
185
|
+
files: tree.files.map(({ path, size, mode }) => ({ path, size, mode })),
|
|
186
|
+
});
|
|
187
|
+
}
|
|
131
188
|
export function validateProjectedSkillTree(targetRoot, expected) {
|
|
132
189
|
const stat = fs.lstatSync(targetRoot);
|
|
133
190
|
if (!stat.isDirectory() || stat.isSymbolicLink())
|
|
134
191
|
throw new Error(`Portable projection target is invalid: ${targetRoot}`);
|
|
135
192
|
const actual = actualTree(targetRoot);
|
|
136
|
-
if (
|
|
193
|
+
if (materializedShape(actual) !== materializedShape(expected)) {
|
|
137
194
|
throw new Error(`Portable projection skill tree mismatch: ${targetRoot}`);
|
|
138
195
|
}
|
|
139
196
|
}
|
|
@@ -51,7 +51,7 @@ export declare class ProjectStore {
|
|
|
51
51
|
refresh(): void;
|
|
52
52
|
/**
|
|
53
53
|
* Create a new user project directory under PROJECTS_DIR with a standard scaffold
|
|
54
|
-
* (STATUS.md +
|
|
54
|
+
* (STATUS.md + AGENTS.md + TASKS.yaml). Validates the name (rejects path traversal, separators,
|
|
55
55
|
* empty/whitespace, leading-dot, and the reserved 'general'). Never overwrites an
|
|
56
56
|
* existing project directory — returns an `already-exists` error instead.
|
|
57
57
|
*/
|
|
@@ -115,7 +115,7 @@ export class ProjectStore {
|
|
|
115
115
|
}
|
|
116
116
|
/**
|
|
117
117
|
* Create a new user project directory under PROJECTS_DIR with a standard scaffold
|
|
118
|
-
* (STATUS.md +
|
|
118
|
+
* (STATUS.md + AGENTS.md + TASKS.yaml). Validates the name (rejects path traversal, separators,
|
|
119
119
|
* empty/whitespace, leading-dot, and the reserved 'general'). Never overwrites an
|
|
120
120
|
* existing project directory — returns an `already-exists` error instead.
|
|
121
121
|
*/
|
|
@@ -165,10 +165,10 @@ export class ProjectStore {
|
|
|
165
165
|
this.ensureTasksFile(generalDir);
|
|
166
166
|
}
|
|
167
167
|
/** Create a project directory and write the standard scaffold files. */
|
|
168
|
-
scaffoldProject(dir, statusContent,
|
|
168
|
+
scaffoldProject(dir, statusContent, indexContent) {
|
|
169
169
|
fs.mkdirSync(dir, { recursive: true });
|
|
170
170
|
fs.writeFileSync(path.join(dir, 'STATUS.md'), statusContent, 'utf8');
|
|
171
|
-
fs.writeFileSync(path.join(dir, '
|
|
171
|
+
fs.writeFileSync(path.join(dir, 'AGENTS.md'), indexContent, 'utf8');
|
|
172
172
|
this.ensureTasksFile(dir);
|
|
173
173
|
}
|
|
174
174
|
ensureTasksFile(dir) {
|
|
@@ -85,7 +85,7 @@ async function main() {
|
|
|
85
85
|
}
|
|
86
86
|
// Step 3: Ship the managed bundle to ~/.cortex/client/current/
|
|
87
87
|
console.log('[3/4] Deploying client bundle...');
|
|
88
|
-
const bundle = resolveBundle();
|
|
88
|
+
const bundle = await resolveBundle();
|
|
89
89
|
if (!bundle) {
|
|
90
90
|
log.error('No client bundle available (dev: client repo build failed; release: npm registry unreachable).');
|
|
91
91
|
process.exit(1);
|
|
@@ -13,7 +13,7 @@ interface PushAttempt {
|
|
|
13
13
|
ok: boolean | null;
|
|
14
14
|
}
|
|
15
15
|
declare function loadBundleFromDir(dir: string, version: string): ClientBundle | null;
|
|
16
|
-
declare function resolveBundle(): ClientBundle | null
|
|
16
|
+
declare function resolveBundle(): Promise<ClientBundle | null>;
|
|
17
17
|
/** Pure decision: push when the device diverges, unless the same bundle is in
|
|
18
18
|
* flight or recently failed on that device. */
|
|
19
19
|
declare function shouldPush(reported: string | null, bundleHash: string, last: PushAttempt | undefined, now: number): boolean;
|