@cortex-agent/server 2026.9.15 → 2026.9.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -2
- package/defaults/config/hooks/08-agents-md-injector-post-tool.json +10 -0
- package/defaults/config/hooks/{10-cortex-md-injector-session-start.json → 10-agents-md-injector-session-start.json} +3 -3
- package/defaults/config/hooks/{CORTEX.md → AGENTS.md} +2 -2
- package/defaults/hooks/{CORTEX.md → AGENTS.md} +1 -1
- package/defaults/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
- package/defaults/hooks/cortex-hook-api.mjs +2 -2
- package/defaults/hooks/new-session-hook.mjs +2 -2
- package/defaults/hooks/rules-loader.mjs +2 -2
- package/defaults/hooks/status-md-guard.mjs +8 -8
- package/defaults/hooks/task-status-check.mjs +18 -76
- package/defaults/hooks/tasks-yaml-guard.mjs +2 -2
- package/defaults/plugins/cortex-feishu/skills/feishu-doc/SKILL.md +1 -1
- package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +2 -2
- package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +4 -4
- package/defaults/plugins/cortex-system/skills/task/SKILL.md +1 -1
- package/defaults/rules/{cortex-md.md → agents-md.md} +4 -4
- package/defaults/rules/decision-records.md +1 -1
- package/defaults/rules/meta-conventions.md +4 -4
- package/defaults/rules/mission-md.md +1 -1
- package/dist/agent-adapter/claude/hooks-builder.js +2 -2
- package/dist/agent-adapter/claude/spawn-args.js +4 -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/types.d.ts +1 -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/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/utils.d.ts +1 -1
- package/dist/core/utils.js +1 -1
- package/dist/domain/executions/registry.d.ts +1 -2
- package/dist/domain/executions/registry.js +0 -3
- package/dist/domain/mcp/bundled-server.js +4 -3
- package/dist/domain/mcp/feishu/file.js +37 -18
- package/dist/domain/mcp/feishu/types.d.ts +3 -0
- package/dist/domain/mcp/feishu-server.js +1 -1
- package/dist/domain/mcp/tools/{cortex-md.d.ts → agents-md.d.ts} +6 -6
- package/dist/domain/mcp/tools/{cortex-md.js → agents-md.js} +6 -6
- package/dist/domain/mcp/tools/remote-file.d.ts +20 -0
- package/dist/domain/mcp/tools/remote-file.js +44 -0
- package/dist/domain/mcp/tools/slack.d.ts +2 -0
- package/dist/domain/mcp/tools/slack.js +22 -7
- package/dist/domain/mcp/tools/task-ops.js +5 -13
- package/dist/domain/mcp/tools/ui-file.js +23 -10
- package/dist/domain/mcp/tools/waitpoint.d.ts +3 -0
- package/dist/domain/mcp/tools/waitpoint.js +122 -0
- package/dist/domain/memory/agents-md-injector.d.ts +24 -0
- package/dist/domain/memory/{cortex-md-injector.js → agents-md-injector.js} +10 -7
- package/dist/domain/projects/project-store.d.ts +1 -1
- package/dist/domain/projects/project-store.js +3 -3
- package/dist/domain/remote/client-hot-reload.js +3 -1
- package/dist/domain/remote/client-manager.js +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/tasks/claim-recovery.js +2 -2
- package/dist/domain/tasks/dispatch-utils.d.ts +10 -1
- package/dist/domain/tasks/dispatch-utils.js +46 -1
- package/dist/domain/tasks/dispatcher.js +4 -5
- package/dist/domain/tasks/mutator.d.ts +2 -2
- package/dist/domain/tasks/mutator.js +2 -2
- package/dist/domain/tasks/system/task-cli.js +2 -2
- package/dist/domain/tasks/system/task-state.js +1 -1
- package/dist/domain/threads/runner.js +3 -1
- package/dist/domain/ui-service/app-router.d.ts +24 -3
- package/dist/domain/ui-service/app-router.js +8 -14
- package/dist/domain/ui-service/input-schemas.d.ts +17 -5
- package/dist/domain/ui-service/input-schemas.js +13 -9
- package/dist/domain/ui-service/mutate/platform-settings.js +1 -1
- package/dist/domain/ui-service/mutate/sessions.d.ts +5 -1
- package/dist/domain/ui-service/mutate/sessions.js +14 -0
- package/dist/domain/ui-service/mutate/waitpoints.d.ts +2 -0
- package/dist/domain/ui-service/mutate/waitpoints.js +20 -0
- package/dist/domain/ui-service/platform-settings.js +1 -1
- package/dist/domain/ui-service/plugins-shared.js +1 -1
- package/dist/domain/ui-service/query/config.js +1 -1
- package/dist/domain/ui-service/query/executions.js +0 -2
- package/dist/domain/ui-service/query/machine-detail.js +3 -8
- package/dist/domain/ui-service/query/memory.js +1 -1
- package/dist/domain/ui-service/query/sessions.js +7 -0
- package/dist/domain/ui-service/query/threads.js +1 -54
- package/dist/domain/ui-service/query/waitpoints.d.ts +30 -0
- package/dist/domain/ui-service/query/waitpoints.js +117 -0
- package/dist/domain/ui-service/query-input-schemas.d.ts +3 -0
- package/dist/domain/ui-service/query-input-schemas.js +3 -0
- package/dist/domain/ui-service/trpc.js +1 -1
- package/dist/domain/ui-service/types.d.ts +133 -49
- package/dist/domain/ui-service/types.js +1 -1
- package/dist/domain/ui-service/ui-service.js +7 -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 +29 -7
- package/dist/entry/auth-login-cli.js +1 -1
- package/dist/entry/auth-login-terminal.js +1 -1
- package/dist/entry/init-auth.js +1 -1
- package/dist/entry/init.js +6 -6
- package/dist/entry/signal-cli.d.ts +30 -0
- package/dist/entry/signal-cli.js +207 -0
- package/dist/entry/start-ui-http.d.ts +1 -1
- package/dist/entry/start-ui-http.js +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 +17 -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 +4 -0
- package/dist/orchestration/conversation-request.js +13 -6
- package/dist/orchestration/interactions/plan-approvals.js +1 -1
- package/dist/orchestration/outputs-store.d.ts +11 -0
- package/dist/orchestration/outputs-store.js +32 -6
- 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 +11 -1
- package/dist/orchestration/thread-input.d.ts +3 -2
- package/dist/orchestration/thread-input.js +8 -9
- package/dist/orchestration/turn/turn-prep.d.ts +15 -1
- package/dist/orchestration/turn/turn-prep.js +19 -8
- 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-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.js +1 -1
- package/dist/store/session-registry-repo.js +1 -1
- 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 +2 -2
- package/web/dist/assets/{index-CRDJo39X.css → index-CwwQNMpP.css} +1 -1
- package/web/dist/assets/index-DLSfgq3o.js +444 -0
- package/web/dist/assets/{index-CEZ0DSei.js → index-DZTuqUO4.js} +1 -1
- package/web/dist/index.html +2 -2
- package/defaults/config/hooks/08-cortex-md-injector-post-tool.json +0 -10
- package/dist/domain/executions/log-tailer.d.ts +0 -71
- package/dist/domain/executions/log-tailer.js +0 -194
- package/dist/domain/memory/cortex-md-injector.d.ts +0 -24
- package/dist/domain/memory/cortex-md-scanner.d.ts +0 -10
- package/dist/domain/memory/cortex-md-scanner.js +0 -66
- package/dist/domain/remote/cortex-client.d.ts +0 -1
- package/dist/domain/remote/cortex-client.js +0 -662
- package/dist/domain/tasks/system/cortex-run.d.ts +0 -25
- package/dist/domain/tasks/system/cortex-run.js +0 -360
- package/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
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
---
|
|
2
2
|
paths:
|
|
3
|
-
- "context/**/
|
|
3
|
+
- "context/**/AGENTS.md"
|
|
4
4
|
---
|
|
5
5
|
|
|
6
|
-
#
|
|
6
|
+
# AGENTS.md Index Convention
|
|
7
7
|
|
|
8
|
-
Directory index + entry map.
|
|
8
|
+
Directory index + entry map. Loaded into the context of every agent that works in this directory — by the backend itself (Claude Code and PI both read `AGENTS.md` natively) and, for paths outside the session working directory, by the `agents-md-injector` hook. The byte count IS the context cost, paid on every session that touches the directory. It answers "what is here, where to look", not "what the content is": each line exists so an agent knows where to read, not as a substitute for reading.
|
|
9
9
|
|
|
10
10
|
## Hard Constraints
|
|
11
11
|
|
|
12
|
-
- **Hard cap: 120 lines AND 8KB** (enforced by guard hook
|
|
12
|
+
- **Hard cap: 120 lines AND 8KB** (enforced by guard hook). The hook path truncates at 9,500 characters, so content past that line is never injected at all — pure waste.
|
|
13
13
|
- **Each index line <=200 characters**: one sentence of purpose + pointer.
|
|
14
14
|
- **One line per atomic directory**: experiments/, knowledge/, patterns/, decisions/ each take a single line in the index, pointing at their auto-generated index.md (or the directory itself). **Never enumerate per-entry summaries** — summaries already live in the atomic files' frontmatter and index.md; copies in the index are pure redundancy.
|
|
15
15
|
|
|
@@ -38,7 +38,7 @@ Evidence: EXP-NNN, EXP-NNN
|
|
|
38
38
|
|
|
39
39
|
**Reference format**: `DR-NNNN` (analogous to `EXP-NNN` and `K-NNN`). Numbering is independent within each level (system-level and each project starts from 0001).
|
|
40
40
|
|
|
41
|
-
**Indexing rule**: After adding a new DR, you must add an inline reference link in the corresponding level's
|
|
41
|
+
**Indexing rule**: After adding a new DR, you must add an inline reference link in the corresponding level's AGENTS.md.
|
|
42
42
|
|
|
43
43
|
## Boundaries with Other Knowledge Types
|
|
44
44
|
|
|
@@ -5,14 +5,14 @@ paths:
|
|
|
5
5
|
|
|
6
6
|
# Context Meta-Rules
|
|
7
7
|
|
|
8
|
-
Cross-file conventions. See the dedicated rule for each file type in the same directory (status-md.md / issues-md.md / mission-md.md / roadmap-md.md / overview-md.md /
|
|
8
|
+
Cross-file conventions. See the dedicated rule for each file type in the same directory (status-md.md / issues-md.md / mission-md.md / roadmap-md.md / overview-md.md / agents-md.md / task-system.md / experiment-format.md / decision-records.md).
|
|
9
9
|
|
|
10
10
|
## General Rules
|
|
11
11
|
|
|
12
12
|
- **All context updates are auto-committed via git**: Incremental commits, each logical unit (experiment configuration, analysis report, status update) is committed upon completion, do not accumulate until the end of the session.
|
|
13
13
|
- **Value traceability**: Every value appearing in STATUS / EXP / K / reports must be traceable — specify the script + data file that produced it, or write inline arithmetic citing the data. Numbers without sources are invalid.
|
|
14
|
-
- **Update index after creating new files**: After creating a new file in any directory, update that directory's
|
|
15
|
-
- **Decision traceability**: Each DR-NNNN within a project adds an inline reference in the project's
|
|
14
|
+
- **Update index after creating new files**: After creating a new file in any directory, update that directory's AGENTS.md index (see agents-md.md).
|
|
15
|
+
- **Decision traceability**: Each DR-NNNN within a project adds an inline reference in the project's AGENTS.md; system-level DRs are referenced in `context/AGENTS.md`.
|
|
16
16
|
|
|
17
17
|
## Index Files
|
|
18
18
|
|
|
@@ -33,7 +33,7 @@ PostToolUse hook automatically records Read/Grep access to atomic files (EXP/K/P
|
|
|
33
33
|
|------|----------------|-------------|
|
|
34
34
|
| `STATUS.md` | status-md.md | Overwrite snapshot (state register), hard limit 80 lines AND 6KB, each bullet <=2 lines |
|
|
35
35
|
| `ISSUES.md` | issues-md.md | Append, resolved entries deleted directly, hard limit 80 lines AND 6KB, each entry <=4 lines |
|
|
36
|
-
| `
|
|
36
|
+
| `AGENTS.md` (directory index) | agents-md.md | Pointer-style index, hard limit 120 lines AND 8KB, one line per atomic directory |
|
|
37
37
|
| `mission.md` | mission-md.md | Modify after user confirmation |
|
|
38
38
|
| `roadmap.md` | roadmap-md.md | Stable, milestones must contain testable checklist |
|
|
39
39
|
| `OVERVIEW.md` | overview-md.md | Synchronous update, hard limit 60 lines |
|
|
@@ -45,4 +45,4 @@ The project's "constitution": defines goals and success conditions. It is the ba
|
|
|
45
45
|
|
|
46
46
|
## Modification Process
|
|
47
47
|
|
|
48
|
-
For major re-orientations: update STATUS / roadmap / project
|
|
48
|
+
For major re-orientations: update STATUS / roadmap / project AGENTS.md in the same pass to avoid context inconsistency.
|
|
@@ -31,10 +31,10 @@ export const POST_TOOL_USE_HOOKS = [
|
|
|
31
31
|
nodeHook('rules-loader.mjs'),
|
|
32
32
|
] },
|
|
33
33
|
{ matcher: 'Read|Edit|Write|Skill', hooks: [nodeHook('session-activity-tracker.mjs')] },
|
|
34
|
-
{ matcher: 'Read|Edit', hooks: [nodeHook('
|
|
34
|
+
{ matcher: 'Read|Edit', hooks: [nodeHook('agents-md-injector.mjs')] },
|
|
35
35
|
];
|
|
36
36
|
export const SESSION_START_HOOKS = [
|
|
37
|
-
{ matcher: 'startup|resume|clear|compact', hooks: [nodeHook('
|
|
37
|
+
{ matcher: 'startup|resume|clear|compact', hooks: [nodeHook('agents-md-injector.mjs')] },
|
|
38
38
|
];
|
|
39
39
|
function buildLegacyHooksSettings() {
|
|
40
40
|
return {
|
|
@@ -310,6 +310,10 @@ export function buildClaudeEnv(channel, sessionId, callbackSource, scheduleTaskI
|
|
|
310
310
|
// CORTEX_SESSION_ID is the stable Cortex tracking id (session-activity log routing + MCP context),
|
|
311
311
|
// NOT the backend CLI's self-assigned session id. Falls back to the backend id when unset (threads).
|
|
312
312
|
env.CORTEX_SESSION_ID = context?.trackSessionId ?? sessionId;
|
|
313
|
+
// Declared, not inferred: hooks branch on which backend loaded the AGENTS.md chain natively
|
|
314
|
+
// (agents-md-injector.mjs), and "absent means Claude" would silently mis-handle any future
|
|
315
|
+
// spawn path that forgets to set it. PI states itself in agent-adapter/pi/session-options.ts.
|
|
316
|
+
env.CORTEX_BACKEND = 'claude';
|
|
313
317
|
setIfPresent(env, 'CORTEX_CALLBACK_SOURCE', callbackSource);
|
|
314
318
|
setIfPresent(env, 'CORTEX_SCHEDULE_TASK_ID', scheduleTaskId);
|
|
315
319
|
setIfPresent(env, 'ANTHROPIC_BASE_URL', anthropicBaseUrl);
|
|
@@ -54,6 +54,17 @@ export interface PendingTurn {
|
|
|
54
54
|
* (the spontaneous turn the CLI emits after a run_in_background task finishes). */
|
|
55
55
|
spontaneous?: boolean;
|
|
56
56
|
}
|
|
57
|
+
/**
|
|
58
|
+
* One `tool_result` content block as a line of transcript text.
|
|
59
|
+
*
|
|
60
|
+
* Text passes through; everything else is DESCRIBED, never serialized. `Read` on an image answers
|
|
61
|
+
* with `[{type:'image', source:{type:'base64', data:<~500 KB>}}]`, and stringifying that put the
|
|
62
|
+
* entire payload into the tool_result event — which becomes a debug transcript row, a subagent
|
|
63
|
+
* notice pushed into the PARENT session's stream (`domain/agents/subagent/runner.ts`, not gated on
|
|
64
|
+
* debug) and a capture-log line. One image read cost ~0.5 MB on each of those paths; the model's
|
|
65
|
+
* own context never carried it, only Cortex's transcript did.
|
|
66
|
+
*/
|
|
67
|
+
export declare function describeResultBlock(item: any): string;
|
|
57
68
|
/**
|
|
58
69
|
* Extract the prompt text from a `--replay-user-messages` echo. `message.content` arrives either
|
|
59
70
|
* as a bare string or as text blocks. Returns null for anything else — notably the tool_result
|
|
@@ -25,16 +25,57 @@ function subagentAttribution(data) {
|
|
|
25
25
|
model: typeof data?.message?.model === 'string' ? data.message.model : null,
|
|
26
26
|
};
|
|
27
27
|
}
|
|
28
|
+
/** Longest serialization one unrecognised result block may contribute. */
|
|
29
|
+
const RESULT_BLOCK_JSON_LIMIT = 1000;
|
|
30
|
+
function formatByteSize(bytes) {
|
|
31
|
+
if (bytes >= 1024 * 1024)
|
|
32
|
+
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
|
33
|
+
if (bytes >= 1024)
|
|
34
|
+
return `${Math.round(bytes / 1024)} KB`;
|
|
35
|
+
return `${bytes} B`;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* One `tool_result` content block as a line of transcript text.
|
|
39
|
+
*
|
|
40
|
+
* Text passes through; everything else is DESCRIBED, never serialized. `Read` on an image answers
|
|
41
|
+
* with `[{type:'image', source:{type:'base64', data:<~500 KB>}}]`, and stringifying that put the
|
|
42
|
+
* entire payload into the tool_result event — which becomes a debug transcript row, a subagent
|
|
43
|
+
* notice pushed into the PARENT session's stream (`domain/agents/subagent/runner.ts`, not gated on
|
|
44
|
+
* debug) and a capture-log line. One image read cost ~0.5 MB on each of those paths; the model's
|
|
45
|
+
* own context never carried it, only Cortex's transcript did.
|
|
46
|
+
*/
|
|
47
|
+
export function describeResultBlock(item) {
|
|
48
|
+
if (typeof item === 'string')
|
|
49
|
+
return item;
|
|
50
|
+
if (!item || typeof item !== 'object')
|
|
51
|
+
return '';
|
|
52
|
+
if (item.type === 'text' && typeof item.text === 'string')
|
|
53
|
+
return item.text;
|
|
54
|
+
if (item.type === 'image' || item.type === 'document') {
|
|
55
|
+
const source = (item.source ?? {});
|
|
56
|
+
const mime = typeof source.media_type === 'string' ? source.media_type : item.type;
|
|
57
|
+
// base64 → bytes: the magnitude is the point, so no decode is worth its cost here.
|
|
58
|
+
if (typeof source.data === 'string')
|
|
59
|
+
return `[${mime}, ${formatByteSize(Math.floor((source.data.length * 3) / 4))}]`;
|
|
60
|
+
if (typeof source.url === 'string')
|
|
61
|
+
return `[${mime}, ${source.url}]`;
|
|
62
|
+
return `[${mime}]`;
|
|
63
|
+
}
|
|
64
|
+
const json = JSON.stringify(item) ?? '';
|
|
65
|
+
return json.length > RESULT_BLOCK_JSON_LIMIT
|
|
66
|
+
? `${json.slice(0, RESULT_BLOCK_JSON_LIMIT)}… [${json.length - RESULT_BLOCK_JSON_LIMIT} more chars]`
|
|
67
|
+
: json;
|
|
68
|
+
}
|
|
28
69
|
/** Flatten a `tool_result` block's content to the string shape every sink expects. Shared by the
|
|
29
70
|
* in-turn path and the orphan-subagent path so the two cannot drift. */
|
|
30
71
|
function toolResultText(block) {
|
|
31
72
|
if (typeof block.content === 'string')
|
|
32
73
|
return block.content;
|
|
33
|
-
if (Array.isArray(block.content))
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
return
|
|
74
|
+
if (Array.isArray(block.content))
|
|
75
|
+
return block.content.map(describeResultBlock).join('\n');
|
|
76
|
+
if (block.content == null)
|
|
77
|
+
return '';
|
|
78
|
+
return describeResultBlock(block.content);
|
|
38
79
|
}
|
|
39
80
|
function subagentActivityKind(data) {
|
|
40
81
|
if (data.type === 'assistant')
|
|
@@ -3,5 +3,20 @@
|
|
|
3
3
|
export interface FileAttachment {
|
|
4
4
|
mimeType: string;
|
|
5
5
|
path: string;
|
|
6
|
+
/** What the user called the file. Optional: an attachment that never had a name (a pasted
|
|
7
|
+
* image) is described by its path alone. Carried separately from `path` because the stored
|
|
8
|
+
* name is ASCII-folded and de-duplicated, so the path is not the name. */
|
|
9
|
+
name?: string;
|
|
6
10
|
}
|
|
7
|
-
|
|
11
|
+
/** An attachment the platform would not hand over, named so the model does not answer as if the
|
|
12
|
+
* user had sent nothing. */
|
|
13
|
+
export interface FailedAttachment {
|
|
14
|
+
name: string;
|
|
15
|
+
reason: string;
|
|
16
|
+
}
|
|
17
|
+
/** The block that names attachments the platform would not hand over, or '' when none did.
|
|
18
|
+
* Exported because the conversation path composes its prompt text itself and must be able to
|
|
19
|
+
* fold the same notice in — an attachment that failed to download used to be logged and then
|
|
20
|
+
* silently forgotten, leaving the agent to answer as if the user had sent nothing. */
|
|
21
|
+
export declare function formatAttachmentFailures(failures: FailedAttachment[]): string;
|
|
22
|
+
export declare function buildPrompt(userMessage: string, files: FileAttachment[], failures?: FailedAttachment[]): string;
|
|
@@ -1,23 +1,41 @@
|
|
|
1
1
|
import { IMAGE_MIMES, VIDEO_MIMES } from '../../core/media-types.js';
|
|
2
2
|
import * as path from 'path';
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
/** The block that names attachments the platform would not hand over, or '' when none did.
|
|
4
|
+
* Exported because the conversation path composes its prompt text itself and must be able to
|
|
5
|
+
* fold the same notice in — an attachment that failed to download used to be logged and then
|
|
6
|
+
* silently forgotten, leaving the agent to answer as if the user had sent nothing. */
|
|
7
|
+
export function formatAttachmentFailures(failures) {
|
|
8
|
+
if (failures.length === 0)
|
|
9
|
+
return '';
|
|
10
|
+
const list = failures.map(f => `${f.name} (${f.reason})`).join('\n');
|
|
11
|
+
return `[${failures.length} attachment(s) the user sent could NOT be downloaded and are `
|
|
12
|
+
+ `unavailable to you. Say so rather than answering as if they had not been sent:\n${list}\n]\n\n`;
|
|
13
|
+
}
|
|
14
|
+
/** `path` for a file stored under its own name; `path (name)` when the two differ. */
|
|
15
|
+
function describe(file) {
|
|
16
|
+
const p = file.path.replace(/\\/g, '/');
|
|
17
|
+
const name = file.name?.trim();
|
|
18
|
+
return name && name !== path.basename(p) ? `${p} (${name})` : p;
|
|
19
|
+
}
|
|
20
|
+
export function buildPrompt(userMessage, files, failures = []) {
|
|
21
|
+
if (files.length === 0 && failures.length === 0)
|
|
5
22
|
return userMessage;
|
|
6
23
|
const imageFiles = files.filter(f => IMAGE_MIMES.has(f.mimeType));
|
|
7
24
|
const videoFiles = files.filter(f => VIDEO_MIMES.has(f.mimeType));
|
|
8
25
|
const otherFiles = files.filter(f => !IMAGE_MIMES.has(f.mimeType) && !VIDEO_MIMES.has(f.mimeType));
|
|
9
26
|
let prefix = '';
|
|
10
27
|
if (imageFiles.length > 0) {
|
|
11
|
-
const paths = imageFiles.map(
|
|
28
|
+
const paths = imageFiles.map(describe).join('\n');
|
|
12
29
|
prefix += `[User sent ${imageFiles.length} image(s). Read these files to view them:\n${paths}\n]\n\n`;
|
|
13
30
|
}
|
|
14
31
|
if (videoFiles.length > 0) {
|
|
15
|
-
const paths = videoFiles.map(
|
|
32
|
+
const paths = videoFiles.map(describe).join('\n');
|
|
16
33
|
prefix += `[User sent ${videoFiles.length} video(s). Read these files to view them:\n${paths}\n]\n\n`;
|
|
17
34
|
}
|
|
18
35
|
if (otherFiles.length > 0) {
|
|
19
|
-
const fileList = otherFiles.map(
|
|
36
|
+
const fileList = otherFiles.map(describe).join('\n');
|
|
20
37
|
prefix += `[User sent ${otherFiles.length} file(s). Read these files:\n${fileList}\n]\n\n`;
|
|
21
38
|
}
|
|
22
|
-
|
|
39
|
+
prefix += formatAttachmentFailures(failures);
|
|
40
|
+
return prefix + (userMessage || (files.length > 0 ? 'Please analyze the attached file(s).' : ''));
|
|
23
41
|
}
|
|
@@ -12,6 +12,7 @@ export const MCP_TOOLS_BY_SERVER = {
|
|
|
12
12
|
'cost_query', 'query_executions', 'cortex_context', 'cortex_schedule_add',
|
|
13
13
|
'cortex_schedule_list', 'cortex_schedule_get', 'cortex_schedule_remove',
|
|
14
14
|
'cortex_schedule_pause', 'cortex_schedule_resume',
|
|
15
|
+
'wait_create', 'wait_check', 'wait_cancel',
|
|
15
16
|
],
|
|
16
17
|
'cortex-interaction-bridge': [
|
|
17
18
|
'cortex_plan_enter', 'cortex_plan_exit',
|
|
@@ -3,3 +3,13 @@
|
|
|
3
3
|
* two sets, so they live below both rather than in either one. */
|
|
4
4
|
export declare const IMAGE_MIMES: Set<string>;
|
|
5
5
|
export declare const VIDEO_MIMES: Set<string>;
|
|
6
|
+
/** The mime a file's first bytes actually declare, or null when they are not a known image.
|
|
7
|
+
*
|
|
8
|
+
* A platform's metadata is a claim, not a fact: Feishu hands every inbound image out as
|
|
9
|
+
* `image_key` with no type at all (Cortex called them all PNG), Slack can mislabel, and a user
|
|
10
|
+
* can rename anything. Backends sniff the bytes themselves, so a wrong mime never broke reading —
|
|
11
|
+
* it broke everything that classifies on the declared value (prompt bucket, UI attachment kind,
|
|
12
|
+
* the extension the file is stored under). */
|
|
13
|
+
export declare function sniffImageMime(head: Buffer): string | null;
|
|
14
|
+
/** The extension an image mime should be stored under, or null for a mime with no fixed one. */
|
|
15
|
+
export declare function imageMimeExtension(mimeType: string): string | null;
|
package/dist/core/media-types.js
CHANGED
|
@@ -3,3 +3,37 @@
|
|
|
3
3
|
* two sets, so they live below both rather than in either one. */
|
|
4
4
|
export const IMAGE_MIMES = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp']);
|
|
5
5
|
export const VIDEO_MIMES = new Set(['video/mp4', 'video/webm', 'video/quicktime', 'video/x-msvideo', 'video/x-matroska']);
|
|
6
|
+
/** Canonical extension per image mime, for naming a file whose declared type turned out to be a lie. */
|
|
7
|
+
const IMAGE_MIME_EXTENSIONS = {
|
|
8
|
+
'image/png': '.png',
|
|
9
|
+
'image/jpeg': '.jpg',
|
|
10
|
+
'image/gif': '.gif',
|
|
11
|
+
'image/webp': '.webp',
|
|
12
|
+
'image/bmp': '.bmp',
|
|
13
|
+
};
|
|
14
|
+
/** The mime a file's first bytes actually declare, or null when they are not a known image.
|
|
15
|
+
*
|
|
16
|
+
* A platform's metadata is a claim, not a fact: Feishu hands every inbound image out as
|
|
17
|
+
* `image_key` with no type at all (Cortex called them all PNG), Slack can mislabel, and a user
|
|
18
|
+
* can rename anything. Backends sniff the bytes themselves, so a wrong mime never broke reading —
|
|
19
|
+
* it broke everything that classifies on the declared value (prompt bucket, UI attachment kind,
|
|
20
|
+
* the extension the file is stored under). */
|
|
21
|
+
export function sniffImageMime(head) {
|
|
22
|
+
if (head.length >= 3 && head[0] === 0xff && head[1] === 0xd8 && head[2] === 0xff)
|
|
23
|
+
return 'image/jpeg';
|
|
24
|
+
if (head.length >= 8 && head.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])))
|
|
25
|
+
return 'image/png';
|
|
26
|
+
if (head.length >= 6 && head.subarray(0, 3).toString('latin1') === 'GIF')
|
|
27
|
+
return 'image/gif';
|
|
28
|
+
if (head.length >= 12
|
|
29
|
+
&& head.subarray(0, 4).toString('latin1') === 'RIFF'
|
|
30
|
+
&& head.subarray(8, 12).toString('latin1') === 'WEBP')
|
|
31
|
+
return 'image/webp';
|
|
32
|
+
if (head.length >= 2 && head.subarray(0, 2).toString('latin1') === 'BM')
|
|
33
|
+
return 'image/bmp';
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
/** The extension an image mime should be stored under, or null for a mime with no fixed one. */
|
|
37
|
+
export function imageMimeExtension(mimeType) {
|
|
38
|
+
return IMAGE_MIME_EXTENSIONS[mimeType] ?? null;
|
|
39
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// input: zod and platform credential field definitions
|
|
2
2
|
// output: platform configuration contract and safe patch schema
|
|
3
3
|
// pos: Browser-safe platform settings boundary
|
|
4
|
-
// >>> Once updated, update this header and parent
|
|
4
|
+
// >>> Once updated, update this header and parent AGENTS.md <<<
|
|
5
5
|
import { z } from 'zod';
|
|
6
6
|
export const PLATFORM_FIELDS = {
|
|
7
7
|
feishu: ['FEISHU_APP_ID', 'FEISHU_APP_SECRET', 'FEISHU_DOMAIN', 'FEISHU_ENCRYPT_KEY', 'FEISHU_VERIFICATION_TOKEN'],
|
|
@@ -29,6 +29,9 @@ export interface Settings {
|
|
|
29
29
|
feishuSkillsInWeb: boolean;
|
|
30
30
|
managerRotateSteps: number;
|
|
31
31
|
waitingSweepMs: number;
|
|
32
|
+
waitpointSweepMs: number;
|
|
33
|
+
waitpointTtlMs: number;
|
|
34
|
+
waitpointMaxWakesPerHour: number;
|
|
32
35
|
injectWaitMaxS: number;
|
|
33
36
|
threadMaxDepth: number;
|
|
34
37
|
taskArtifactTemplates: string[];
|
|
@@ -186,6 +189,24 @@ export declare const SETTINGS_SPEC: {
|
|
|
186
189
|
default: number;
|
|
187
190
|
legacyParse: (raw: string) => number;
|
|
188
191
|
};
|
|
192
|
+
waitpointSweepMs: {
|
|
193
|
+
envVar: string;
|
|
194
|
+
type: "number";
|
|
195
|
+
default: number;
|
|
196
|
+
legacyParse: (raw: string) => number;
|
|
197
|
+
};
|
|
198
|
+
waitpointTtlMs: {
|
|
199
|
+
envVar: string;
|
|
200
|
+
type: "number";
|
|
201
|
+
default: number;
|
|
202
|
+
legacyParse: (raw: string) => number;
|
|
203
|
+
};
|
|
204
|
+
waitpointMaxWakesPerHour: {
|
|
205
|
+
envVar: string;
|
|
206
|
+
type: "number";
|
|
207
|
+
default: number;
|
|
208
|
+
legacyParse: (raw: string) => number;
|
|
209
|
+
};
|
|
189
210
|
injectWaitMaxS: {
|
|
190
211
|
envVar: string;
|
|
191
212
|
type: "number";
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// input: raw environment and runtime setting policy shapes
|
|
2
2
|
// output: settings types, defaults, parsers and validators
|
|
3
3
|
// pos: Browser-safe runtime settings contract
|
|
4
|
-
// >>> Once updated, update this header and parent
|
|
4
|
+
// >>> Once updated, update this header and parent AGENTS.md <<<
|
|
5
5
|
export const MAX_TIMER_DELAY_MS = 2_147_483_647;
|
|
6
6
|
export const MAX_SESSION_RETENTION_DAYS = Math.floor(Number.MAX_SAFE_INTEGER / 86_400_000);
|
|
7
7
|
function validateJobInterval(value) {
|
|
@@ -160,6 +160,33 @@ export const SETTINGS_SPEC = {
|
|
|
160
160
|
return Number.isFinite(value) ? value : 60_000;
|
|
161
161
|
},
|
|
162
162
|
},
|
|
163
|
+
waitpointSweepMs: {
|
|
164
|
+
envVar: 'CORTEX_WAITPOINT_SWEEP_MS',
|
|
165
|
+
type: 'number',
|
|
166
|
+
default: 30_000,
|
|
167
|
+
legacyParse: (raw) => {
|
|
168
|
+
const value = Number.parseInt(raw || '', 10);
|
|
169
|
+
return Number.isFinite(value) ? value : 30_000;
|
|
170
|
+
},
|
|
171
|
+
},
|
|
172
|
+
waitpointTtlMs: {
|
|
173
|
+
envVar: 'CORTEX_WAITPOINT_TTL_MS',
|
|
174
|
+
type: 'number',
|
|
175
|
+
default: 7 * 24 * 60 * 60 * 1000,
|
|
176
|
+
legacyParse: (raw) => {
|
|
177
|
+
const value = Number.parseInt(raw || '', 10);
|
|
178
|
+
return Number.isFinite(value) && value > 0 ? value : 7 * 24 * 60 * 60 * 1000;
|
|
179
|
+
},
|
|
180
|
+
},
|
|
181
|
+
waitpointMaxWakesPerHour: {
|
|
182
|
+
envVar: 'CORTEX_WAITPOINT_MAX_WAKES_PER_HOUR',
|
|
183
|
+
type: 'number',
|
|
184
|
+
default: 12,
|
|
185
|
+
legacyParse: (raw) => {
|
|
186
|
+
const value = Number.parseInt(raw || '', 10);
|
|
187
|
+
return Number.isFinite(value) && value > 0 ? value : 12;
|
|
188
|
+
},
|
|
189
|
+
},
|
|
163
190
|
injectWaitMaxS: {
|
|
164
191
|
envVar: 'CORTEX_INJECT_WAIT_MAX_S',
|
|
165
192
|
type: 'number',
|
|
@@ -31,7 +31,9 @@ export type SystemTurnOrigin =
|
|
|
31
31
|
/** A subtask escalated a question to the manager session (`ask_manager`). */
|
|
32
32
|
| 'subtask-question'
|
|
33
33
|
/** A backgrounded `agent` run delivered its result. */
|
|
34
|
-
| 'agent-result'
|
|
34
|
+
| 'agent-result'
|
|
35
|
+
/** A waitpoint an agent armed was resolved by a signal from outside the process. */
|
|
36
|
+
| 'external-signal';
|
|
35
37
|
export interface AuthNoticeAction {
|
|
36
38
|
kind: 'auth-login';
|
|
37
39
|
noticeId: string;
|
package/dist/core/utils.d.ts
CHANGED
|
@@ -16,7 +16,7 @@ declare function todayISO(): string;
|
|
|
16
16
|
* List subdirectories of PROJECTS_DIR that look like project folders.
|
|
17
17
|
*
|
|
18
18
|
* Filters out:
|
|
19
|
-
* - non-directories (e.g. top-level files like
|
|
19
|
+
* - non-directories (e.g. top-level files like AGENTS.md, AGENTS.md that
|
|
20
20
|
* some users keep next to their projects/ tree)
|
|
21
21
|
* - dotfiles (.git, .obsidian, etc.)
|
|
22
22
|
*
|
package/dist/core/utils.js
CHANGED
|
@@ -74,7 +74,7 @@ function todayISO() {
|
|
|
74
74
|
* List subdirectories of PROJECTS_DIR that look like project folders.
|
|
75
75
|
*
|
|
76
76
|
* Filters out:
|
|
77
|
-
* - non-directories (e.g. top-level files like
|
|
77
|
+
* - non-directories (e.g. top-level files like AGENTS.md, AGENTS.md that
|
|
78
78
|
* some users keep next to their projects/ tree)
|
|
79
79
|
* - dotfiles (.git, .obsidian, etc.)
|
|
80
80
|
*
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { executionRepo, TERMINAL_STATUSES } from '../../store/execution-repo.js';
|
|
2
2
|
import type { AgentResult } from '../../core/types/agent-types.js';
|
|
3
|
-
export type { ExecutionRecord, DispatchInfo
|
|
3
|
+
export type { ExecutionRecord, DispatchInfo } from '../../store/execution-repo.js';
|
|
4
4
|
export { TERMINAL_STATUSES };
|
|
5
5
|
/** Release any task locks owned by `executionId` WITHOUT ending the execution.
|
|
6
6
|
* Used by the thread suspend path (DR-0014): a manager that acquired a project lock
|
|
@@ -18,7 +18,6 @@ export declare function findRunningDispatchMatch(opts: Parameters<typeof executi
|
|
|
18
18
|
export declare function startLocalExecution(opts: Parameters<typeof executionRepo.startLocalExecution>[0]): import("../../store/execution-repo.js").ExecutionRecord;
|
|
19
19
|
export declare function registerDispatchExecution(opts: Parameters<typeof executionRepo.registerDispatchExecution>[0]): import("../../store/execution-repo.js").ExecutionRecord;
|
|
20
20
|
export declare function touchExecution(id: string, patch?: Parameters<typeof executionRepo.touchExecution>[1]): import("../../store/execution-repo.js").ExecutionRecord;
|
|
21
|
-
export declare function setExecutionGpuByTaskId(taskId: string, gpu: Parameters<typeof executionRepo.setExecutionGpuByTaskId>[1]): import("../../store/execution-repo.js").ExecutionRecord;
|
|
22
21
|
export declare function completeExecution(id: string, metrics?: Parameters<typeof executionRepo.completeExecution>[1]): import("../../store/execution-repo.js").ExecutionRecord;
|
|
23
22
|
export declare function completeExecutionByTaskId(taskId: string, metrics?: Parameters<typeof executionRepo.completeExecutionByTaskId>[1]): import("../../store/execution-repo.js").ExecutionRecord;
|
|
24
23
|
export declare function failExecution(id: string, metrics?: Parameters<typeof executionRepo.failExecution>[1]): import("../../store/execution-repo.js").ExecutionRecord;
|
|
@@ -82,9 +82,6 @@ export function registerDispatchExecution(opts) {
|
|
|
82
82
|
export function touchExecution(id, patch) {
|
|
83
83
|
return executionRepo.touchExecution(id, patch);
|
|
84
84
|
}
|
|
85
|
-
export function setExecutionGpuByTaskId(taskId, gpu) {
|
|
86
|
-
return executionRepo.setExecutionGpuByTaskId(taskId, gpu);
|
|
87
|
-
}
|
|
88
85
|
export function completeExecution(id, metrics) {
|
|
89
86
|
const r = executionRepo.completeExecution(id, metrics);
|
|
90
87
|
if (r && TERMINAL_STATUSES.has(r.status))
|
|
@@ -32,15 +32,16 @@ const threadLoader = async (ctx) => {
|
|
|
32
32
|
return server => { registerThreadTools(server, ctx); registerAskManagerTool(server, ctx); };
|
|
33
33
|
};
|
|
34
34
|
const extLoader = async (ctx) => {
|
|
35
|
-
const [{ registerCostTools }, { registerExecutionTools }, { registerContextTools }, { registerScheduleTools }] = await Promise.all([
|
|
35
|
+
const [{ registerCostTools }, { registerExecutionTools }, { registerContextTools }, { registerScheduleTools }, { registerWaitpointTools }] = await Promise.all([
|
|
36
36
|
import('./tools/cost.js'), import('./tools/executions.js'), import('./tools/context.js'),
|
|
37
|
-
import('./tools/schedule.js'),
|
|
37
|
+
import('./tools/schedule.js'), import('./tools/waitpoint.js'),
|
|
38
38
|
]);
|
|
39
39
|
return server => {
|
|
40
40
|
registerCostTools(server);
|
|
41
41
|
registerExecutionTools(server);
|
|
42
42
|
registerContextTools(server, ctx);
|
|
43
43
|
registerScheduleTools(server, ctx);
|
|
44
|
+
registerWaitpointTools(server, ctx);
|
|
44
45
|
};
|
|
45
46
|
};
|
|
46
47
|
const interactionLoader = async (ctx) => {
|
|
@@ -65,7 +66,7 @@ const feishuLoader = async (ctx) => {
|
|
|
65
66
|
]);
|
|
66
67
|
// App credentials stay process-wide (one Feishu app per daemon); only the channel is per session.
|
|
67
68
|
const client = buildFeishuClientFromEnv();
|
|
68
|
-
return server => registerFeishuTools(server, { client, fallbackChannel: ctx.channel });
|
|
69
|
+
return server => registerFeishuTools(server, { client, fallbackChannel: ctx.channel, ctx });
|
|
69
70
|
};
|
|
70
71
|
const webLoader = async (ctx) => {
|
|
71
72
|
const [{ registerUiFileTools }, { registerUiViewTools }, { registerUiDecisionTools }] = await Promise.all([
|
|
@@ -2,6 +2,8 @@ import { z } from 'zod';
|
|
|
2
2
|
import * as fs from 'fs';
|
|
3
3
|
import * as path from 'path';
|
|
4
4
|
import { guard, ok, unwrap } from './types.js';
|
|
5
|
+
import { uploadFeishuImage } from '../../../platform/adapters/feishu-image.js';
|
|
6
|
+
import { withStagedRemoteFile } from '../tools/remote-file.js';
|
|
5
7
|
function resolveReadableFilePath(filePathInput) {
|
|
6
8
|
const resolved = path.isAbsolute(filePathInput)
|
|
7
9
|
? filePathInput
|
|
@@ -43,51 +45,68 @@ function inferFeishuFileType(fileName) {
|
|
|
43
45
|
// Use 'stream' as fallback for all unsupported types
|
|
44
46
|
return typeMap[ext] || 'stream';
|
|
45
47
|
}
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
const body = fs.readFileSync(resolved);
|
|
49
|
-
const uploadName = fileName || path.basename(resolved);
|
|
50
|
-
// Strip 'feishu:' prefix from channel ID for Feishu API compatibility
|
|
51
|
-
const bareChannel = stripFeishuPrefix(channel);
|
|
52
|
-
// Upload file to get file_key
|
|
48
|
+
/** Upload as a chat file and return its file_key. */
|
|
49
|
+
async function uploadFileKey(client, resolved, uploadName) {
|
|
53
50
|
const uploadRes = await client.im.v1.file.create({
|
|
54
51
|
data: {
|
|
55
52
|
file_type: inferFeishuFileType(uploadName),
|
|
56
53
|
file_name: uploadName,
|
|
57
|
-
file:
|
|
54
|
+
file: fs.readFileSync(resolved),
|
|
58
55
|
},
|
|
59
56
|
});
|
|
60
57
|
const fileKey = unwrap(uploadRes).file_key;
|
|
61
58
|
if (!fileKey)
|
|
62
59
|
throw new Error('Feishu file upload failed: no file_key returned');
|
|
63
|
-
|
|
64
|
-
|
|
60
|
+
return fileKey;
|
|
61
|
+
}
|
|
62
|
+
export async function uploadFileToFeishu(client, { channel, filePath, fileName, title }) {
|
|
63
|
+
const { resolved, size } = resolveReadableFilePath(filePath);
|
|
64
|
+
const uploadName = fileName || path.basename(resolved);
|
|
65
|
+
// Strip 'feishu:' prefix from channel ID for Feishu API compatibility
|
|
66
|
+
const bareChannel = stripFeishuPrefix(channel);
|
|
67
|
+
// An image goes into the chat as an image, so the user sees it without opening anything. The file
|
|
68
|
+
// card below stays the fallback: non-images, images over 10 MB, and apps without `im:resource`.
|
|
69
|
+
const imageKey = await uploadFeishuImage(client, resolved, size);
|
|
70
|
+
const msgType = imageKey ? 'image' : 'file';
|
|
71
|
+
const msgContent = imageKey
|
|
72
|
+
? JSON.stringify({ image_key: imageKey })
|
|
73
|
+
: JSON.stringify({ file_key: await uploadFileKey(client, resolved, uploadName) });
|
|
65
74
|
await client.im.v1.message.create({
|
|
66
75
|
params: { receive_id_type: 'chat_id' },
|
|
67
76
|
data: {
|
|
68
77
|
receive_id: bareChannel,
|
|
69
|
-
msg_type:
|
|
78
|
+
msg_type: msgType,
|
|
70
79
|
content: msgContent,
|
|
71
80
|
},
|
|
72
81
|
});
|
|
73
82
|
return { path: resolved, fileName: uploadName, size };
|
|
74
83
|
}
|
|
75
84
|
export function registerFileTools(server, deps) {
|
|
76
|
-
server.tool('feishu_send_file', 'Upload a
|
|
77
|
-
file_path: z.string().describe('Local
|
|
85
|
+
server.tool('feishu_send_file', 'Upload a file to Feishu. Use this when you need to share a file (document, image, archive, etc.) with users in a Feishu chat or channel. The file may be on this server or, with `device`, on a connected remote device.', {
|
|
86
|
+
file_path: z.string().describe('File path to upload. Local path, or an absolute path on `device`.'),
|
|
78
87
|
file_name: z.string().optional().describe('Optional filename override shown in Feishu'),
|
|
79
88
|
title: z.string().optional().describe('Optional file title shown in Feishu'),
|
|
80
89
|
channel: z.string().optional().describe('Optional chat/channel ID (uses route context if not provided)'),
|
|
81
|
-
|
|
90
|
+
device: z.string().optional().describe('Name of a connected remote device (as used by remote_bash). Omit for files on this server.'),
|
|
91
|
+
}, async ({ file_path, file_name, title, channel: explicitChannel, device }) => guard(deps.client, async (client) => {
|
|
82
92
|
const channel = explicitChannel || deps.fallbackChannel || '';
|
|
83
93
|
if (!channel)
|
|
84
94
|
throw new Error('No Feishu channel available (no session channel or channel parameter)');
|
|
85
|
-
const
|
|
95
|
+
const upload = (filePath, name) => uploadFileToFeishu(client, {
|
|
86
96
|
channel,
|
|
87
|
-
filePath
|
|
88
|
-
fileName:
|
|
97
|
+
filePath,
|
|
98
|
+
fileName: name,
|
|
89
99
|
title,
|
|
90
100
|
});
|
|
91
|
-
|
|
101
|
+
// The Feishu upload reads from a path, so a device's file is staged to disk first and
|
|
102
|
+
// removed again once the upload has taken its bytes.
|
|
103
|
+
if (!device) {
|
|
104
|
+
const uploaded = await upload(file_path, file_name);
|
|
105
|
+
return ok(`File uploaded: ${uploaded.fileName} (${uploaded.size} bytes)`);
|
|
106
|
+
}
|
|
107
|
+
if (!deps.ctx)
|
|
108
|
+
throw new Error('`device` is not available in this context');
|
|
109
|
+
const uploaded = await withStagedRemoteFile(deps.ctx, device, file_path, staged => upload(staged.localPath, file_name || staged.name));
|
|
110
|
+
return ok(`File uploaded from ${device}: ${uploaded.fileName} (${uploaded.size} bytes)`);
|
|
92
111
|
}));
|
|
93
112
|
}
|
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import type { LarkClient } from './client.js';
|
|
2
|
+
import type { CortexToolContext } from '../tools/context.js';
|
|
2
3
|
/** Dependencies injected into each register*Tools function (client is mockable in tests). */
|
|
3
4
|
export interface FeishuToolDeps {
|
|
4
5
|
client: LarkClient | null;
|
|
5
6
|
/** Session channel used when a tool call names none (may carry the `feishu:` prefix). */
|
|
6
7
|
fallbackChannel?: string | null;
|
|
8
|
+
/** Carried so the file tool can reach the daemon to stage a remote device's file. */
|
|
9
|
+
ctx?: CortexToolContext;
|
|
7
10
|
}
|
|
8
11
|
export interface McpResult {
|
|
9
12
|
content: Array<{
|
|
@@ -18,7 +18,7 @@ const client = buildFeishuClientFromEnv();
|
|
|
18
18
|
// --- McpServer + tool registration ---
|
|
19
19
|
const ctx = toolContextFromEnv();
|
|
20
20
|
const server = new McpServer({ name: 'cortex-feishu', version: CORTEX_VERSION });
|
|
21
|
-
registerGatedMcpTools(server, target => registerFeishuTools(target, { client, fallbackChannel: ctx.channel }), ctx.toolAllowlist);
|
|
21
|
+
registerGatedMcpTools(server, target => registerFeishuTools(target, { client, fallbackChannel: ctx.channel, ctx }), ctx.toolAllowlist);
|
|
22
22
|
export async function startServer() {
|
|
23
23
|
if (!client) {
|
|
24
24
|
log.warn('FEISHU_APP_ID / FEISHU_APP_SECRET not set — feishu_send_file will return a not-configured error');
|