claude-code-session-manager 0.139.0 → 0.141.0
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 +20 -4
- package/dist/assets/AppSettings-DExeJhqQ.js +2 -0
- package/dist/assets/History-DJMiuXyK.js +2 -0
- package/dist/assets/{HomeClaudeConfig-CGD2Onjv.js → HomeClaudeConfig-CTp2tkZ4.js} +2 -2
- package/dist/assets/{Panel-Csyd9HbD.js → Panel-Bf1Cf8UL.js} +1 -1
- package/dist/assets/{ProjectClaudeConfig-C-jlYpC_.js → ProjectClaudeConfig-BWPpypf9.js} +1 -1
- package/dist/assets/Scheduler-cyr61UAC.js +16 -0
- package/dist/assets/{SkillReferenceGraph-DcscPXAG.js → SkillReferenceGraph-Ba4TkX2C.js} +1 -1
- package/dist/assets/{Skills-BpGRKOcY.js → Skills-C1v91GEO.js} +26 -26
- package/dist/assets/{TiptapBody-DSU3769X.js → TiptapBody-BrcWVpiW.js} +1 -1
- package/dist/assets/{ViewTabs-C0PRZx4_.js → ViewTabs-DXhOWFG0.js} +1 -1
- package/dist/assets/{VoiceButton-D2rMurNg.js → VoiceButton-qivnDV6K.js} +1 -1
- package/dist/assets/{historyTotals-TcIQs2sh.js → historyTotals-CMCPTKqC.js} +1 -1
- package/dist/assets/index-B2TQz3nd.js +3121 -0
- package/dist/assets/{index-BCySPdtU.css → index-DKXdXfka.css} +1 -1
- package/dist/index.html +2 -2
- package/dist-web/app.css +1 -1
- package/dist-web/app.js +423 -426
- package/package.json +5 -2
- package/plugins/AGENTS.md +60 -0
- package/plugins/CLAUDE.md +1 -60
- package/plugins/session-manager-dev/skills/builder/SKILL.md +4 -2
- package/plugins/session-manager-dev/skills/develop/SKILL.md +29 -19
- package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +5 -4
- package/plugins/session-manager-dev/skills/maintaining-md-network/audit.md +4 -2
- package/plugins/session-manager-dev/skills/maintaining-md-network/drift-check.md +16 -12
- package/plugins/session-manager-dev/skills/maintaining-md-network/migrate-to-agents-md.md +15 -0
- package/plugins/session-manager-dev/skills/maintaining-md-network/placement.md +50 -2
- package/plugins/session-manager-dev/skills/maintaining-md-network/plan.md +10 -10
- package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/drift-check.cjs +117 -112
- package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdDuplicates.cjs +182 -0
- package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdLinks.cjs +340 -0
- package/scripts/README.md +1 -0
- package/scripts/hooks/guard-tool-risk.cjs +91 -0
- package/scripts/hooks/lib/guard-tool-risk-policy.cjs +217 -0
- package/scripts/ops-sweep.cjs +53 -23
- package/scripts/scheduler-mcp-server.cjs +205 -18
- package/src/main/build-info.json +4 -4
- package/src/main/config.cjs +112 -8
- package/src/main/docEdit.cjs +6 -1
- package/src/main/files.cjs +7 -27
- package/src/main/health.cjs +48 -15
- package/src/main/historyAggregator.cjs +88 -5
- package/src/main/historyDashboard.cjs +69 -4
- package/src/main/index.cjs +56 -2
- package/src/main/ipcSchemas.cjs +122 -16
- package/src/main/lib/AGENTS.md +54 -0
- package/src/main/lib/CLAUDE.md +1 -54
- package/src/main/lib/agent-cli/adapters/codex.cjs +5 -2
- package/src/main/lib/agent-cli/agentCliIpc.cjs +18 -2
- package/src/main/lib/agent-cli/agentCliSessionStore.cjs +1 -0
- package/src/main/lib/agent-cli/agentCliTurn.cjs +20 -2
- package/src/main/lib/agent-cli/geminiContextDefaults.cjs +94 -0
- package/src/main/lib/claude/effectiveModelInfo.cjs +90 -20
- package/src/main/lib/claude/jobSandboxPolicy.cjs +202 -0
- package/src/main/lib/claude/personaToolScope.cjs +12 -6
- package/src/main/lib/claude/rateLimitDetect.cjs +13 -2
- package/src/main/lib/claude/runClaudeP.cjs +6 -1
- package/src/main/lib/claude/toolRiskIpc.cjs +177 -0
- package/src/main/lib/claude/toolRiskMarks.cjs +373 -0
- package/src/main/lib/demo-video-kit/seedKit.cjs +27 -6
- package/src/main/lib/ephemeralCwd.cjs +37 -2
- package/src/main/lib/epic/delegationReadiness.cjs +42 -9
- package/src/main/lib/epic/epicAdminRoutes.cjs +25 -5
- package/src/main/lib/epic/epicOutsideRead.cjs +118 -1
- package/src/main/lib/epic/epicOutsideState.cjs +2 -2
- package/src/main/lib/epic/epicSweepValidator.cjs +7 -2
- package/src/main/lib/epic/epicValidationHook.cjs +24 -4
- package/src/main/lib/epic/guardSpawnSettings.cjs +57 -1
- package/src/main/lib/externalContract.cjs +31 -5
- package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +55 -1
- package/src/main/lib/feedback-remote/crossProjectReply.cjs +106 -11
- package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +47 -19
- package/src/main/lib/feedback-remote/needsYouStore.cjs +6 -2
- package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +98 -1
- package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +5 -0
- package/src/main/lib/git/branchSweep.cjs +209 -4
- package/src/main/lib/git/gitWorktree.cjs +41 -5
- package/src/main/lib/guardShims.cjs +1 -1
- package/src/main/lib/historyRollup.cjs +26 -0
- package/src/main/lib/insideHome.cjs +27 -1
- package/src/main/lib/mcpToolCatalog.cjs +132 -13
- package/src/main/lib/mdDocCensus.cjs +59 -78
- package/src/main/lib/mdDocRefs.cjs +71 -93
- package/src/main/lib/mdNetworkScan.cjs +245 -250
- package/src/main/lib/mdReviewRecord.cjs +22 -9
- package/src/main/lib/memoryMdNetwork.cjs +5 -12
- package/src/main/lib/opsOwnership.cjs +18 -2
- package/src/main/lib/opsRetentionSettings.cjs +28 -4
- package/src/main/lib/persona-macro/macroJobDispatch.cjs +90 -20
- package/src/main/lib/persona-macro/macroJobIpc.cjs +144 -46
- package/src/main/lib/persona-macro/macroJobStatus.cjs +87 -9
- package/src/main/lib/persona-macro/macroLibrary.cjs +95 -5
- package/src/main/lib/persona-macro/personaImportHealth.cjs +78 -17
- package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +96 -0
- package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
- package/src/main/lib/prd/depSlugResolve.cjs +104 -4
- package/src/main/lib/prd/prdAdminRoutes.cjs +35 -2
- package/src/main/lib/prd/prdCreate.cjs +377 -23
- package/src/main/lib/prd/prdDisposition.cjs +11 -2
- package/src/main/lib/prd/prdFrontmatter.cjs +121 -3
- package/src/main/lib/process/loginItem.cjs +171 -0
- package/src/main/lib/process/loginItemPlan.cjs +193 -0
- package/src/main/lib/project-pages/playerBridge.cjs +4 -0
- package/src/main/lib/project-pages/videoReview.cjs +268 -0
- package/src/main/lib/project-pages/videoReviewIpc.cjs +229 -0
- package/src/main/lib/scheduler/cpuSample.cjs +131 -4
- package/src/main/lib/scheduler/fixPlanSlug.cjs +4 -3
- package/src/main/lib/scheduler/loadGate.cjs +24 -6
- package/src/main/lib/scheduler/planRecordHarvest.cjs +108 -0
- package/src/main/lib/scheduler/planRecordRetention.cjs +144 -0
- package/src/main/lib/scheduler/preflightCheck.cjs +97 -0
- package/src/main/lib/scheduler/queueStore.cjs +7 -0
- package/src/main/lib/scheduler/rcaReport.cjs +21 -1
- package/src/main/lib/scheduler/reaperHelpers.cjs +35 -5
- package/src/main/lib/scheduler/reviewNotice.cjs +39 -0
- package/src/main/lib/scheduler/runLogRetention.cjs +104 -3
- package/src/main/lib/scheduler/scheduleJobSchema.cjs +3 -0
- package/src/main/lib/scheduler/schedulerBatch.cjs +25 -48
- package/src/main/lib/scheduler/schedulerPaths.cjs +3 -0
- package/src/main/lib/scheduler/sessionSlots.cjs +176 -21
- package/src/main/lib/scheduler/validationQuality.cjs +282 -0
- package/src/main/lib/scheduler/validatorVerdictSchema.cjs +254 -0
- package/src/main/lib/tasks/taskAdminRoutes.cjs +641 -0
- package/src/main/lib/tasks/taskIpc.cjs +80 -0
- package/src/main/lib/tasks/taskLedger.cjs +502 -0
- package/src/main/lib/tasks/taskRun.cjs +313 -0
- package/src/main/lib/tasks/taskSwitch.cjs +120 -0
- package/src/main/loginItemIpc.cjs +35 -0
- package/src/main/loopEfficiencyHandlers.cjs +10 -1
- package/src/main/projectPages.cjs +6 -15
- package/src/main/promptSessionEvents.cjs +9 -1
- package/src/main/queueOps.cjs +260 -3
- package/src/main/runVerify.cjs +53 -25
- package/src/main/scheduler/AGENTS.md +26 -0
- package/src/main/scheduler/CLAUDE.md +1 -26
- package/src/main/scheduler/budget.cjs +239 -9
- package/src/main/scheduler/cancelDependents.cjs +154 -0
- package/src/main/scheduler/prdParser.cjs +19 -1
- package/src/main/scheduler/reviewLadder.cjs +36 -3
- package/src/main/scheduler/starvation.cjs +89 -18
- package/src/main/scheduler.cjs +1080 -89
- package/src/main/supervisor.cjs +5 -1
- package/src/main/templates/PRD_AUTHORING.md +14 -1
- package/src/main/validationQualityHandlers.cjs +199 -0
- package/src/main/webRemote.cjs +10 -2
- package/src/preload/api.d.ts +364 -21
- package/src/preload/apiSurface.json +89 -10
- package/src/preload/index.cjs +23 -2
- package/src/seed/agents/validator.md +19 -8
- package/dist/assets/AppSettings-CUfWY9vN.js +0 -2
- package/dist/assets/History-DDnqaLyw.js +0 -2
- package/dist/assets/Scheduler-NLs08fx7.js +0 -16
- package/dist/assets/index-C-d0DCre.js +0 -3124
|
@@ -0,0 +1,641 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* taskAdminRoutes.cjs — the admin HTTP face of the Task primitive.
|
|
3
|
+
*
|
|
4
|
+
* POST /admin/tasks
|
|
5
|
+
* Run ONE headless `claude -p` for a project, under the machine-wide slot
|
|
6
|
+
* cap, recorded in that project's Task ledger. Order:
|
|
7
|
+
* 1. strict body schema (400 invalid_request), sessionId+resume /
|
|
8
|
+
* resume+persistSession:false / missing mcpConfig file (400);
|
|
9
|
+
* 2. the human switch 'Scripts may run Tasks' (403 tasks_disabled);
|
|
10
|
+
* 3. persona → model + effort with the SPAWN-time resolvers
|
|
11
|
+
* (agentModelResolve.cjs / agentEffortResolve.cjs — never
|
|
12
|
+
* FALLBACK_MODEL, never effectiveModelInfo.cjs): 404 unknown_agent,
|
|
13
|
+
* 422 model_unresolved, 422 effort_unresolved. The persona BODY is
|
|
14
|
+
* never read into the prompt or argv;
|
|
15
|
+
* 4. 409 session_busy when another running Task holds the session;
|
|
16
|
+
* 5. ledger start line, THEN sessionSlots.waitForSlot by priority lane
|
|
17
|
+
* (null → 'slot_timeout', too_many_waiting → 429);
|
|
18
|
+
* 6. taskRun.runTask, token released in finally, ledger end line with
|
|
19
|
+
* costUsd from modelPricing.costOfUsage;
|
|
20
|
+
* 7. 200 { ok: true, taskId, status, stdout, envelope, usage, costUsd,
|
|
21
|
+
* cliCostUsd, durationMs, slotWaitMs, exitCode, model, effort,
|
|
22
|
+
* sessionId, quota }.
|
|
23
|
+
* A req/res 'close' before the reply aborts the wait or the run
|
|
24
|
+
* ('caller_gone'); the route disables the socket timeout (runs are long).
|
|
25
|
+
*
|
|
26
|
+
* GET /admin/tasks?cwd=&since=&until=&pipeline=&runId=&step=&agent=&status=&source=&limit=&offset=
|
|
27
|
+
* → { ok, tasks, total, hasMore } from taskLedger.listTasks. Each task has
|
|
28
|
+
* exactly TASK_FIELDS (no prompt/output text). Works whatever the switch.
|
|
29
|
+
* GET /admin/task?cwd=&id=
|
|
30
|
+
* → { ok, task } — TASK_FIELDS plus prompt, output, stderrTail, envelope
|
|
31
|
+
* (and the truncation flags) from the body file; 404 unknown_task.
|
|
32
|
+
* POST /admin/tasks/import (body ≤ 8 MiB)
|
|
33
|
+
* { cwd, records: 1-100 } — direct `claude -p` calls a caller made while
|
|
34
|
+
* Session Manager was down. 403 tasks_disabled when the switch is off.
|
|
35
|
+
* Each record is validated on its own and recorded with
|
|
36
|
+
* taskLedger.appendImported (source 'direct'); a known (cwd, importId) is
|
|
37
|
+
* skipped. costUsd is recomputed with costOfUsage when usage is present
|
|
38
|
+
* (the caller's figure is kept as cliCostUsd).
|
|
39
|
+
* → { ok, imported, alreadyImported, rejected: [{ index, error }] }.
|
|
40
|
+
* Read and import routes take a cwd that must be a project root (400).
|
|
41
|
+
*
|
|
42
|
+
* No caller environment variable ever reaches the child (buildTaskEnv adds
|
|
43
|
+
* only the Task markers to process.env). Auth/loopback binding are the
|
|
44
|
+
* injected localAdminHttp.cjs transport's job (see index.cjs).
|
|
45
|
+
*/
|
|
46
|
+
'use strict';
|
|
47
|
+
|
|
48
|
+
const fs = require('node:fs');
|
|
49
|
+
const path = require('node:path');
|
|
50
|
+
const crypto = require('node:crypto');
|
|
51
|
+
const { z } = require('zod');
|
|
52
|
+
const { readBody, sendJson } = require('../feedback-remote/localAdminHttp.cjs');
|
|
53
|
+
const { resolveProjectRoot } = require('../opsOwnership.cjs');
|
|
54
|
+
|
|
55
|
+
const MAX_BODY_BYTES = 4 * 1024 * 1024;
|
|
56
|
+
const MAX_IMPORT_BODY_BYTES = 8 * 1024 * 1024;
|
|
57
|
+
const MAX_IMPORT_RECORDS = 100;
|
|
58
|
+
const MAX_SYSTEM_PROMPT_BYTES = 100 * 1024;
|
|
59
|
+
const SWITCH_HINT = "Turn on 'Scripts may run Tasks' for this project on the Scheduler → Tasks page (a human-only switch).";
|
|
60
|
+
|
|
61
|
+
function isAbsoluteDir(p) {
|
|
62
|
+
if (typeof p !== 'string' || !path.isAbsolute(p)) return false;
|
|
63
|
+
try { return fs.statSync(p).isDirectory(); } catch { return false; }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const runtimeSchema = z.object({
|
|
67
|
+
outputFormat: z.enum(['json', 'text', 'stream-json']).default('json'),
|
|
68
|
+
settingSources: z.string().optional(),
|
|
69
|
+
mcpConfig: z.array(z.string().min(1)).optional(),
|
|
70
|
+
strictMcpConfig: z.boolean().optional(),
|
|
71
|
+
// An empty array is valid: it means "deny all".
|
|
72
|
+
allowedTools: z.array(z.string()).optional(),
|
|
73
|
+
tools: z.array(z.string()).optional(),
|
|
74
|
+
maxTurns: z.number().int().min(1).max(200).optional(),
|
|
75
|
+
systemPrompt: z.string()
|
|
76
|
+
.refine((s) => Buffer.byteLength(s, 'utf8') <= MAX_SYSTEM_PROMPT_BYTES, { message: `systemPrompt exceeds ${MAX_SYSTEM_PROMPT_BYTES} bytes` })
|
|
77
|
+
.optional(),
|
|
78
|
+
skipPermissions: z.boolean().optional(),
|
|
79
|
+
disableAutoMemory: z.boolean().optional(),
|
|
80
|
+
sessionId: z.string().uuid().optional(),
|
|
81
|
+
resume: z.string().uuid().optional(),
|
|
82
|
+
persistSession: z.boolean().optional(),
|
|
83
|
+
cwd: z.string().refine(isAbsoluteDir, { message: 'runtime.cwd must be an absolute existing directory' }).optional(),
|
|
84
|
+
}).strict();
|
|
85
|
+
|
|
86
|
+
const bodySchema = z.object({
|
|
87
|
+
cwd: z.string().min(1),
|
|
88
|
+
agent: z.string().min(1).max(200),
|
|
89
|
+
missionId: z.string().min(1).max(200),
|
|
90
|
+
prompt: z.string().min(1),
|
|
91
|
+
timeoutSec: z.number().int().min(1).max(3600).default(600),
|
|
92
|
+
slotWaitSec: z.number().int().min(0).max(3600).default(120),
|
|
93
|
+
priority: z.enum(['interactive', 'batch']).default('batch'),
|
|
94
|
+
caller: z.object({
|
|
95
|
+
pipeline: z.string().max(200).optional(),
|
|
96
|
+
runId: z.string().max(200).optional(),
|
|
97
|
+
step: z.string().max(200).optional(),
|
|
98
|
+
attempt: z.number().int().min(0).optional(),
|
|
99
|
+
}).strict().default({}),
|
|
100
|
+
runtime: runtimeSchema.default({ outputFormat: 'json' }),
|
|
101
|
+
}).strict();
|
|
102
|
+
|
|
103
|
+
/** Outcome statuses an imported record may carry: the ledger's end statuses (taskRun + route). */
|
|
104
|
+
const IMPORT_STATUSES = /** @type {const} */ ([
|
|
105
|
+
'ok', 'error', 'rate_limited', 'timeout', 'spawn_failed', 'caller_gone', 'slot_timeout', 'too_many_waiting', 'interrupted',
|
|
106
|
+
]);
|
|
107
|
+
|
|
108
|
+
/** The keys of one Task in GET /admin/tasks (and the summary part of GET /admin/task). */
|
|
109
|
+
const TASK_FIELDS = Object.freeze([
|
|
110
|
+
'taskId', 'source', 'importId', 'importedAt', 'agent', 'missionId', 'model', 'effort', 'priority', 'caller',
|
|
111
|
+
'outputFormat', 'timeoutSec', 'slotWaitSec', 'sessionId', 'persisted', 'startedAt', 'endedAt', 'status',
|
|
112
|
+
'exitCode', 'signal', 'durationMs', 'slotWaitMs', 'usage', 'costUsd', 'cliCostUsd', 'numTurns', 'quota',
|
|
113
|
+
'promptBytes', 'promptSha256', 'outputBytes', 'outputSha256',
|
|
114
|
+
]);
|
|
115
|
+
|
|
116
|
+
/** @param {Record<string, any>} t a folded ledger Task → exactly TASK_FIELDS (missing → null). */
|
|
117
|
+
function publicTask(t) {
|
|
118
|
+
/** @type {Record<string, any>} */
|
|
119
|
+
const out = {};
|
|
120
|
+
for (const k of TASK_FIELDS) out[k] = t[k] === undefined ? null : t[k];
|
|
121
|
+
if (!out.source) out.source = 'sm';
|
|
122
|
+
if (out.caller == null) out.caller = {};
|
|
123
|
+
out.persisted = t.persisted === true;
|
|
124
|
+
return out;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const isoDate = z.string().refine((s) => /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/.test(s) && Number.isFinite(Date.parse(s)), { message: 'must be an ISO date' });
|
|
128
|
+
|
|
129
|
+
const listQuerySchema = z.object({
|
|
130
|
+
cwd: z.string().min(1),
|
|
131
|
+
since: isoDate.optional(),
|
|
132
|
+
until: isoDate.optional(),
|
|
133
|
+
pipeline: z.string().max(200).optional(),
|
|
134
|
+
runId: z.string().max(200).optional(),
|
|
135
|
+
step: z.string().max(200).optional(),
|
|
136
|
+
agent: z.string().max(200).optional(),
|
|
137
|
+
status: z.string().max(100).optional(),
|
|
138
|
+
source: z.enum(['sm', 'direct']).optional(),
|
|
139
|
+
limit: z.string().regex(/^\d+$/).transform(Number).pipe(z.number().int().min(1).max(200)).optional(),
|
|
140
|
+
offset: z.string().regex(/^\d+$/).transform(Number).pipe(z.number().int().min(0)).optional(),
|
|
141
|
+
}).strict();
|
|
142
|
+
|
|
143
|
+
const getQuerySchema = z.object({
|
|
144
|
+
cwd: z.string().min(1),
|
|
145
|
+
id: z.string().min(1).max(200),
|
|
146
|
+
}).strict();
|
|
147
|
+
|
|
148
|
+
const callerSchema = z.object({
|
|
149
|
+
pipeline: z.string().max(200).optional(),
|
|
150
|
+
runId: z.string().max(200).optional(),
|
|
151
|
+
step: z.string().max(200).optional(),
|
|
152
|
+
attempt: z.number().int().min(0).optional(),
|
|
153
|
+
}).strict();
|
|
154
|
+
|
|
155
|
+
const usageNumber = z.number().int().min(0).optional();
|
|
156
|
+
const importRecordSchema = z.object({
|
|
157
|
+
importId: z.string().min(1).max(200),
|
|
158
|
+
agent: z.string().min(1).max(200).optional(),
|
|
159
|
+
model: z.string().min(1).max(200),
|
|
160
|
+
effort: z.string().min(1).max(50).optional(),
|
|
161
|
+
missionId: z.string().min(1).max(200),
|
|
162
|
+
caller: callerSchema.optional(),
|
|
163
|
+
startedAt: isoDate,
|
|
164
|
+
durationMs: z.number().int().min(0),
|
|
165
|
+
status: z.enum(IMPORT_STATUSES),
|
|
166
|
+
exitCode: z.number().int().nullable().optional(),
|
|
167
|
+
usage: z.object({
|
|
168
|
+
input_tokens: usageNumber,
|
|
169
|
+
output_tokens: usageNumber,
|
|
170
|
+
cache_read_input_tokens: usageNumber,
|
|
171
|
+
cache_creation_input_tokens: usageNumber,
|
|
172
|
+
}).passthrough().optional(),
|
|
173
|
+
costUsd: z.number().min(0).nullable().optional(),
|
|
174
|
+
sessionId: z.string().uuid().optional(),
|
|
175
|
+
persisted: z.boolean().optional(),
|
|
176
|
+
prompt: z.string().optional(),
|
|
177
|
+
output: z.string().optional(),
|
|
178
|
+
envelope: z.unknown().optional(),
|
|
179
|
+
}).strict().refine((r) => r.persisted !== true || Boolean(r.sessionId), { message: 'persisted: true needs a sessionId' });
|
|
180
|
+
|
|
181
|
+
const importBodySchema = z.object({
|
|
182
|
+
cwd: z.string().min(1),
|
|
183
|
+
records: z.array(z.unknown()).min(1).max(MAX_IMPORT_RECORDS),
|
|
184
|
+
}).strict();
|
|
185
|
+
|
|
186
|
+
/** First zod issue as one line: "<path>: <message>". */
|
|
187
|
+
function issueText(/** @type {any} */ error) {
|
|
188
|
+
const i = error && error.issues && error.issues[0];
|
|
189
|
+
if (!i) return 'invalid record';
|
|
190
|
+
return `${i.path && i.path.length ? `${i.path.join('.')}: ` : ''}${i.message}`;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Default persona resolution — the spawn-time resolvers chatRunner.cjs uses.
|
|
195
|
+
* `personaFound` comes from agentLibrary.getPersonaBody (whose body is
|
|
196
|
+
* discarded here); model = persona `model` (overlay-aware) else the Settings
|
|
197
|
+
* model — never agentModelResolve's FALLBACK_MODEL.
|
|
198
|
+
* @param {{ cwd: string, agent: string }} a
|
|
199
|
+
* @returns {Promise<{ personaFound: boolean, resolvedModelId: string|null, personaEffort: string|null }>}
|
|
200
|
+
*/
|
|
201
|
+
async function defaultResolveInfo({ cwd, agent }) {
|
|
202
|
+
const { getPersonaBody } = require('../../agentLibrary.cjs');
|
|
203
|
+
const persona = await getPersonaBody({ cwd, name: agent });
|
|
204
|
+
if (!persona) return { personaFound: false, resolvedModelId: null, personaEffort: null };
|
|
205
|
+
const { readOverlayAwarePersonaModel } = require('../claude/agentModelResolve.cjs');
|
|
206
|
+
const { resolveEpicEffort } = require('../claude/agentEffortResolve.cjs');
|
|
207
|
+
const { readSettingsModel } = require('../claude/modelCatalog.cjs');
|
|
208
|
+
let model = readOverlayAwarePersonaModel(agent, { cwd });
|
|
209
|
+
if (!model || model === 'inherit') model = readSettingsModel(cwd);
|
|
210
|
+
const { effort } = resolveEpicEffort({ cwd, agentType: agent });
|
|
211
|
+
return { personaFound: true, resolvedModelId: model || null, personaEffort: effort || null };
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** A real `--model` value: a non-empty string that is not the 'inherit' sentinel. */
|
|
215
|
+
function isConcreteModel(m) {
|
|
216
|
+
return typeof m === 'string' && m.trim() !== '' && m.trim() !== 'inherit';
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** Price the run: the first concrete model the CLI reported, else the model we passed. */
|
|
220
|
+
function costFor(model, run, costOfUsage) {
|
|
221
|
+
const u = run && run.usage;
|
|
222
|
+
if (!u || typeof u !== 'object') return null;
|
|
223
|
+
const reported = run.modelUsage && typeof run.modelUsage === 'object' ? Object.keys(run.modelUsage)[0] : null;
|
|
224
|
+
const cc = u.cache_creation && typeof u.cache_creation === 'object' ? u.cache_creation : null;
|
|
225
|
+
const bucket = {
|
|
226
|
+
inputTokens: u.input_tokens,
|
|
227
|
+
outputTokens: u.output_tokens,
|
|
228
|
+
cacheReadTokens: u.cache_read_input_tokens,
|
|
229
|
+
cacheCreationTokens: u.cache_creation_input_tokens,
|
|
230
|
+
...(cc && typeof cc.ephemeral_1h_input_tokens === 'number' ? { cacheCreation1hTokens: cc.ephemeral_1h_input_tokens } : {}),
|
|
231
|
+
};
|
|
232
|
+
try {
|
|
233
|
+
const r = costOfUsage(reported || model, bucket);
|
|
234
|
+
return r && typeof r.costUsd === 'number' ? r.costUsd : null;
|
|
235
|
+
} catch {
|
|
236
|
+
return null;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* @param {{ registerRoute: Function }} adminHttp
|
|
242
|
+
* @param {{ taskSwitch?: any, resolveInfo?: Function, sessionSlots?: any, runTask?: Function,
|
|
243
|
+
* buildTaskArgs?: Function, buildTaskEnv?: Function, ledger?: any, costOfUsage?: Function,
|
|
244
|
+
* now?: () => number, randomUUID?: () => string, resolveProjectRoot?: Function }} [deps]
|
|
245
|
+
*/
|
|
246
|
+
function registerAdminRoute(adminHttp, deps = {}) {
|
|
247
|
+
// Lazy defaults: agentLibrary / slots / spawn pull in heavy modules.
|
|
248
|
+
const taskSwitch = () => deps.taskSwitch || require('./taskSwitch.cjs');
|
|
249
|
+
const resolveInfo = deps.resolveInfo || defaultResolveInfo;
|
|
250
|
+
const slots = () => deps.sessionSlots || require('../scheduler/sessionSlots.cjs');
|
|
251
|
+
const taskRun = () => require('./taskRun.cjs');
|
|
252
|
+
const runTask = (/** @type {any} */ o) => (deps.runTask || taskRun().runTask)(o);
|
|
253
|
+
const buildArgs = (/** @type {any} */ o) => (deps.buildTaskArgs || taskRun().buildTaskArgs)(o);
|
|
254
|
+
const buildEnv = (/** @type {any} */ rt, /** @type {any} */ env) => (deps.buildTaskEnv || taskRun().buildTaskEnv)(rt, env);
|
|
255
|
+
const ledger = () => deps.ledger || require('./taskLedger.cjs');
|
|
256
|
+
const costOfUsage = (/** @type {any} */ m, /** @type {any} */ b) => (deps.costOfUsage || require('../claude/modelPricing.cjs').costOfUsage)(m, b);
|
|
257
|
+
const now = deps.now || Date.now;
|
|
258
|
+
const newId = deps.randomUUID || (() => crypto.randomUUID());
|
|
259
|
+
const projectRoot = deps.resolveProjectRoot || resolveProjectRoot;
|
|
260
|
+
|
|
261
|
+
/** sessionId → taskId for every Task currently between its start line and its end line. */
|
|
262
|
+
const busySessions = new Map();
|
|
263
|
+
|
|
264
|
+
adminHttp.registerRoute('POST', '/admin/tasks', async (/** @type {any} */ req, /** @type {any} */ res) => {
|
|
265
|
+
try { if (typeof res.setTimeout === 'function') res.setTimeout(0); } catch { /* */ }
|
|
266
|
+
try { if (typeof req.setTimeout === 'function') req.setTimeout(0); } catch { /* */ }
|
|
267
|
+
|
|
268
|
+
let replied = false;
|
|
269
|
+
const reply = (/** @type {number} */ status, /** @type {any} */ obj) => {
|
|
270
|
+
if (replied) return;
|
|
271
|
+
replied = true;
|
|
272
|
+
if (res.writableEnded || res.destroyed) return;
|
|
273
|
+
sendJson(res, status, obj);
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
let raw;
|
|
277
|
+
try {
|
|
278
|
+
raw = await readBody(req, MAX_BODY_BYTES);
|
|
279
|
+
} catch (e) {
|
|
280
|
+
reply(400, { ok: false, error: 'invalid_request', details: e instanceof Error ? e.message : String(e) });
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
let parsedJson;
|
|
284
|
+
try {
|
|
285
|
+
parsedJson = JSON.parse(raw || '{}');
|
|
286
|
+
} catch (e) {
|
|
287
|
+
reply(400, { ok: false, error: 'invalid_request', details: 'body is not valid JSON' });
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
const parsed = bodySchema.safeParse(parsedJson);
|
|
291
|
+
if (!parsed.success) {
|
|
292
|
+
reply(400, { ok: false, error: 'invalid_request', details: parsed.error.issues });
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
const input = parsed.data;
|
|
296
|
+
/** @type {Record<string, any>} */
|
|
297
|
+
const runtime = { ...input.runtime };
|
|
298
|
+
|
|
299
|
+
let cwd;
|
|
300
|
+
try {
|
|
301
|
+
cwd = projectRoot(input.cwd);
|
|
302
|
+
} catch (e) {
|
|
303
|
+
reply(400, { ok: false, error: 'invalid_request', details: e instanceof Error ? e.message : String(e) });
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
if (runtime.sessionId && runtime.resume) {
|
|
307
|
+
reply(400, { ok: false, error: 'invalid_request', details: 'runtime.sessionId and runtime.resume are mutually exclusive' });
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
if (runtime.resume && runtime.persistSession === false) {
|
|
311
|
+
reply(400, { ok: false, error: 'invalid_request', details: 'runtime.resume always persists the session; persistSession:false contradicts it' });
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
if (Array.isArray(runtime.mcpConfig)) {
|
|
315
|
+
const missing = runtime.mcpConfig.map((p) => path.resolve(cwd, p)).filter((p) => !fs.existsSync(p));
|
|
316
|
+
if (missing.length) {
|
|
317
|
+
reply(400, { ok: false, error: 'mcp_config_missing', details: missing });
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
if (!taskSwitch().isTaskSwitchOn(cwd)) {
|
|
323
|
+
reply(403, { ok: false, error: 'tasks_disabled', hint: SWITCH_HINT });
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
const info = await resolveInfo({ cwd, agent: input.agent });
|
|
328
|
+
if (!info || !info.personaFound) {
|
|
329
|
+
reply(404, { ok: false, error: 'unknown_agent', agent: input.agent });
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
const model = info.resolvedModelId;
|
|
333
|
+
if (!isConcreteModel(model)) {
|
|
334
|
+
reply(422, { ok: false, error: 'model_unresolved', agent: input.agent });
|
|
335
|
+
return;
|
|
336
|
+
}
|
|
337
|
+
const effort = info.personaEffort;
|
|
338
|
+
if (typeof effort !== 'string' || !effort.trim()) {
|
|
339
|
+
reply(422, { ok: false, error: 'effort_unresolved', agent: input.agent });
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
const taskId = newId();
|
|
344
|
+
if (runtime.persistSession === true && !runtime.sessionId && !runtime.resume) runtime.sessionId = taskId;
|
|
345
|
+
const sessionId = runtime.sessionId || runtime.resume || null;
|
|
346
|
+
const persisted = runtime.persistSession === true || Boolean(runtime.resume);
|
|
347
|
+
|
|
348
|
+
if (sessionId && busySessions.has(sessionId)) {
|
|
349
|
+
reply(409, { ok: false, error: 'session_busy', sessionId, heldBy: busySessions.get(sessionId) });
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// buildTaskArgs' flag name for the permission bypass.
|
|
354
|
+
const argsRuntime = { ...runtime };
|
|
355
|
+
delete argsRuntime.skipPermissions;
|
|
356
|
+
delete argsRuntime.cwd;
|
|
357
|
+
if (runtime.skipPermissions === true) argsRuntime.dangerouslySkipPermissions = true;
|
|
358
|
+
|
|
359
|
+
let args;
|
|
360
|
+
try {
|
|
361
|
+
args = buildArgs({ model, effort, runtime: argsRuntime, projectCwd: cwd });
|
|
362
|
+
} catch (e) {
|
|
363
|
+
reply(400, { ok: false, error: (e && /** @type {any} */ (e).code) || 'invalid_request', details: e instanceof Error ? e.message : String(e) });
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
const env = buildEnv(runtime, process.env);
|
|
367
|
+
|
|
368
|
+
const ac = new AbortController();
|
|
369
|
+
const onClose = () => { if (!replied) ac.abort(); };
|
|
370
|
+
req.on('close', onClose);
|
|
371
|
+
res.on('close', onClose);
|
|
372
|
+
|
|
373
|
+
const startedMs = now();
|
|
374
|
+
const startedAt = new Date(startedMs).toISOString();
|
|
375
|
+
if (sessionId) busySessions.set(sessionId, taskId);
|
|
376
|
+
try {
|
|
377
|
+
await ledger().appendTaskStart(cwd, {
|
|
378
|
+
taskId,
|
|
379
|
+
startedAt,
|
|
380
|
+
agent: input.agent,
|
|
381
|
+
missionId: input.missionId,
|
|
382
|
+
model,
|
|
383
|
+
effort,
|
|
384
|
+
priority: input.priority,
|
|
385
|
+
timeoutSec: input.timeoutSec,
|
|
386
|
+
slotWaitSec: input.slotWaitSec,
|
|
387
|
+
caller: input.caller,
|
|
388
|
+
outputFormat: runtime.outputFormat,
|
|
389
|
+
sessionId,
|
|
390
|
+
persisted,
|
|
391
|
+
prompt: input.prompt,
|
|
392
|
+
});
|
|
393
|
+
|
|
394
|
+
const end = (/** @type {Record<string, any>} */ row) => ledger().appendTaskEnd(cwd, {
|
|
395
|
+
taskId,
|
|
396
|
+
startedAt,
|
|
397
|
+
endedAt: new Date(now()).toISOString(),
|
|
398
|
+
model,
|
|
399
|
+
sessionId,
|
|
400
|
+
persisted,
|
|
401
|
+
...row,
|
|
402
|
+
});
|
|
403
|
+
|
|
404
|
+
const lane = input.priority === 'interactive' ? 'task-interactive' : 'task-batch';
|
|
405
|
+
const waitStart = now();
|
|
406
|
+
let token;
|
|
407
|
+
try {
|
|
408
|
+
token = await slots().waitForSlot(`task:${taskId}`, { lane, timeoutMs: input.slotWaitSec * 1000, signal: ac.signal });
|
|
409
|
+
} catch (e) {
|
|
410
|
+
const code = (e && /** @type {any} */ (e).code) || 'slot_error';
|
|
411
|
+
await end({ status: code, slotWaitMs: now() - waitStart });
|
|
412
|
+
reply(code === 'too_many_waiting' ? 429 : 500, { ok: false, error: code, taskId });
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
const slotWaitMs = now() - waitStart;
|
|
416
|
+
if (token == null) {
|
|
417
|
+
const status = ac.signal.aborted ? 'caller_gone' : 'slot_timeout';
|
|
418
|
+
await end({ status, slotWaitMs });
|
|
419
|
+
reply(503, { ok: false, error: status, taskId, slotWaitMs });
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
let run;
|
|
424
|
+
try {
|
|
425
|
+
run = await runTask({
|
|
426
|
+
args,
|
|
427
|
+
env,
|
|
428
|
+
prompt: input.prompt,
|
|
429
|
+
cwd: runtime.cwd || cwd,
|
|
430
|
+
timeoutMs: input.timeoutSec * 1000,
|
|
431
|
+
signal: ac.signal,
|
|
432
|
+
onSpawn: (/** @type {number} */ pid) => { try { slots().stampPid(token, pid); } catch { /* */ } },
|
|
433
|
+
});
|
|
434
|
+
} finally {
|
|
435
|
+
try { slots().release(token); } catch { /* */ }
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
const costUsd = costFor(model, run, costOfUsage);
|
|
439
|
+
const finalSessionId = sessionId || run.sessionId || null;
|
|
440
|
+
await end({
|
|
441
|
+
status: run.status,
|
|
442
|
+
exitCode: run.exitCode,
|
|
443
|
+
signal: run.signal,
|
|
444
|
+
durationMs: run.durationMs,
|
|
445
|
+
slotWaitMs,
|
|
446
|
+
usage: run.usage,
|
|
447
|
+
costUsd,
|
|
448
|
+
cliCostUsd: run.cliCostUsd,
|
|
449
|
+
numTurns: run.numTurns,
|
|
450
|
+
quota: run.quota,
|
|
451
|
+
sessionId: finalSessionId,
|
|
452
|
+
output: run.stdout,
|
|
453
|
+
stderrTail: run.stderrTail,
|
|
454
|
+
envelope: run.envelope,
|
|
455
|
+
});
|
|
456
|
+
|
|
457
|
+
const { textStdoutFor } = taskRun();
|
|
458
|
+
reply(200, {
|
|
459
|
+
ok: true,
|
|
460
|
+
taskId,
|
|
461
|
+
status: run.status,
|
|
462
|
+
stdout: runtime.outputFormat === 'text' ? textStdoutFor(run.envelope) : run.stdout,
|
|
463
|
+
envelope: run.envelope,
|
|
464
|
+
usage: run.usage,
|
|
465
|
+
costUsd,
|
|
466
|
+
cliCostUsd: run.cliCostUsd,
|
|
467
|
+
durationMs: run.durationMs,
|
|
468
|
+
slotWaitMs,
|
|
469
|
+
exitCode: run.exitCode,
|
|
470
|
+
model,
|
|
471
|
+
effort,
|
|
472
|
+
sessionId: finalSessionId,
|
|
473
|
+
quota: run.quota,
|
|
474
|
+
});
|
|
475
|
+
} finally {
|
|
476
|
+
if (sessionId && busySessions.get(sessionId) === taskId) busySessions.delete(sessionId);
|
|
477
|
+
req.removeListener('close', onClose);
|
|
478
|
+
res.removeListener('close', onClose);
|
|
479
|
+
}
|
|
480
|
+
});
|
|
481
|
+
|
|
482
|
+
/** @returns {string} the project root, or throws when `cwd` is not one. */
|
|
483
|
+
const rootOf = (/** @type {string} */ cwd) => {
|
|
484
|
+
const root = projectRoot(cwd, { opsInternal: 'refuse' });
|
|
485
|
+
if (path.resolve(root) !== path.resolve(cwd)) throw new Error(`cwd is not a project root (its root is "${root}")`);
|
|
486
|
+
return root;
|
|
487
|
+
};
|
|
488
|
+
|
|
489
|
+
adminHttp.registerRoute('GET', '/admin/tasks', async (/** @type {any} */ _req, /** @type {any} */ res, /** @type {any} */ query) => {
|
|
490
|
+
const parsed = listQuerySchema.safeParse(Object.fromEntries(query ?? []));
|
|
491
|
+
if (!parsed.success) {
|
|
492
|
+
sendJson(res, 400, { ok: false, error: 'invalid_request', details: parsed.error.issues });
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
495
|
+
const { cwd: rawCwd, ...filters } = parsed.data;
|
|
496
|
+
let cwd;
|
|
497
|
+
try { cwd = rootOf(rawCwd); } catch (e) {
|
|
498
|
+
sendJson(res, 400, { ok: false, error: 'invalid_request', details: e instanceof Error ? e.message : String(e) });
|
|
499
|
+
return;
|
|
500
|
+
}
|
|
501
|
+
try {
|
|
502
|
+
const r = await ledger().listTasks(cwd, { ...filters, now: now() });
|
|
503
|
+
sendJson(res, 200, { ok: true, tasks: r.tasks.map(publicTask), total: r.total, hasMore: r.hasMore });
|
|
504
|
+
} catch (e) {
|
|
505
|
+
sendJson(res, 500, { ok: false, error: 'ledger_read_failed', details: e instanceof Error ? e.message : String(e) });
|
|
506
|
+
}
|
|
507
|
+
});
|
|
508
|
+
|
|
509
|
+
adminHttp.registerRoute('GET', '/admin/task', async (/** @type {any} */ _req, /** @type {any} */ res, /** @type {any} */ query) => {
|
|
510
|
+
const parsed = getQuerySchema.safeParse(Object.fromEntries(query ?? []));
|
|
511
|
+
if (!parsed.success) {
|
|
512
|
+
sendJson(res, 400, { ok: false, error: 'invalid_request', details: parsed.error.issues });
|
|
513
|
+
return;
|
|
514
|
+
}
|
|
515
|
+
let cwd;
|
|
516
|
+
try { cwd = rootOf(parsed.data.cwd); } catch (e) {
|
|
517
|
+
sendJson(res, 400, { ok: false, error: 'invalid_request', details: e instanceof Error ? e.message : String(e) });
|
|
518
|
+
return;
|
|
519
|
+
}
|
|
520
|
+
let t;
|
|
521
|
+
try {
|
|
522
|
+
t = await ledger().getTask(cwd, parsed.data.id, { now: now() });
|
|
523
|
+
} catch (e) {
|
|
524
|
+
sendJson(res, 500, { ok: false, error: 'ledger_read_failed', details: e instanceof Error ? e.message : String(e) });
|
|
525
|
+
return;
|
|
526
|
+
}
|
|
527
|
+
if (!t) {
|
|
528
|
+
sendJson(res, 404, { ok: false, error: 'unknown_task', id: parsed.data.id });
|
|
529
|
+
return;
|
|
530
|
+
}
|
|
531
|
+
const body = t.body || {};
|
|
532
|
+
sendJson(res, 200, {
|
|
533
|
+
ok: true,
|
|
534
|
+
task: {
|
|
535
|
+
...publicTask(t),
|
|
536
|
+
prompt: typeof body.prompt === 'string' ? body.prompt : null,
|
|
537
|
+
promptTruncated: body.promptTruncated === true,
|
|
538
|
+
output: typeof body.output === 'string' ? body.output : null,
|
|
539
|
+
outputTruncated: body.outputTruncated === true,
|
|
540
|
+
stderrTail: typeof body.stderrTail === 'string' ? body.stderrTail : null,
|
|
541
|
+
envelope: body.envelope === undefined ? null : body.envelope,
|
|
542
|
+
},
|
|
543
|
+
});
|
|
544
|
+
});
|
|
545
|
+
|
|
546
|
+
/** project root → tail of its import chain: concurrent imports of one project run one at a time (dedupe stays exact). */
|
|
547
|
+
const importChains = new Map();
|
|
548
|
+
|
|
549
|
+
adminHttp.registerRoute('POST', '/admin/tasks/import', async (/** @type {any} */ req, /** @type {any} */ res) => {
|
|
550
|
+
let raw;
|
|
551
|
+
try {
|
|
552
|
+
raw = await readBody(req, MAX_IMPORT_BODY_BYTES);
|
|
553
|
+
} catch (e) {
|
|
554
|
+
sendJson(res, 400, { ok: false, error: 'invalid_request', details: e instanceof Error ? e.message : String(e) });
|
|
555
|
+
return;
|
|
556
|
+
}
|
|
557
|
+
let json;
|
|
558
|
+
try { json = JSON.parse(raw || '{}'); } catch {
|
|
559
|
+
sendJson(res, 400, { ok: false, error: 'invalid_request', details: 'body is not valid JSON' });
|
|
560
|
+
return;
|
|
561
|
+
}
|
|
562
|
+
const parsed = importBodySchema.safeParse(json);
|
|
563
|
+
if (!parsed.success) {
|
|
564
|
+
sendJson(res, 400, { ok: false, error: 'invalid_request', details: parsed.error.issues });
|
|
565
|
+
return;
|
|
566
|
+
}
|
|
567
|
+
let cwd;
|
|
568
|
+
try { cwd = rootOf(parsed.data.cwd); } catch (e) {
|
|
569
|
+
sendJson(res, 400, { ok: false, error: 'invalid_request', details: e instanceof Error ? e.message : String(e) });
|
|
570
|
+
return;
|
|
571
|
+
}
|
|
572
|
+
if (!taskSwitch().isTaskSwitchOn(cwd)) {
|
|
573
|
+
sendJson(res, 403, { ok: false, error: 'tasks_disabled', hint: SWITCH_HINT });
|
|
574
|
+
return;
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
const work = async () => {
|
|
578
|
+
let imported = 0;
|
|
579
|
+
let alreadyImported = 0;
|
|
580
|
+
/** @type {{ index: number, error: string }[]} */
|
|
581
|
+
const rejected = [];
|
|
582
|
+
const seen = new Set();
|
|
583
|
+
const records = parsed.data.records;
|
|
584
|
+
for (let index = 0; index < records.length; index += 1) {
|
|
585
|
+
const r = importRecordSchema.safeParse(records[index]);
|
|
586
|
+
if (!r.success) { rejected.push({ index, error: issueText(r.error) }); continue; }
|
|
587
|
+
const rec = r.data;
|
|
588
|
+
try {
|
|
589
|
+
if (seen.has(rec.importId) || await ledger().hasImport(cwd, rec.importId)) {
|
|
590
|
+
alreadyImported += 1;
|
|
591
|
+
continue;
|
|
592
|
+
}
|
|
593
|
+
seen.add(rec.importId);
|
|
594
|
+
const startedMs = Date.parse(rec.startedAt);
|
|
595
|
+
const priced = rec.usage ? costFor(rec.model, { usage: rec.usage }, costOfUsage) : null;
|
|
596
|
+
const callerCost = typeof rec.costUsd === 'number' ? rec.costUsd : null;
|
|
597
|
+
await ledger().appendImported(cwd, {
|
|
598
|
+
taskId: newId(),
|
|
599
|
+
importId: rec.importId,
|
|
600
|
+
importedAt: new Date(now()).toISOString(),
|
|
601
|
+
agent: rec.agent ?? null,
|
|
602
|
+
missionId: rec.missionId,
|
|
603
|
+
model: rec.model,
|
|
604
|
+
effort: rec.effort ?? null,
|
|
605
|
+
caller: rec.caller ?? {},
|
|
606
|
+
startedAt: new Date(startedMs).toISOString(),
|
|
607
|
+
endedAt: new Date(startedMs + rec.durationMs).toISOString(),
|
|
608
|
+
durationMs: rec.durationMs,
|
|
609
|
+
status: rec.status,
|
|
610
|
+
exitCode: rec.exitCode ?? null,
|
|
611
|
+
usage: rec.usage ?? null,
|
|
612
|
+
costUsd: rec.usage ? (priced ?? callerCost) : callerCost,
|
|
613
|
+
cliCostUsd: callerCost,
|
|
614
|
+
sessionId: rec.sessionId ?? null,
|
|
615
|
+
persisted: rec.persisted === true,
|
|
616
|
+
prompt: rec.prompt ?? '',
|
|
617
|
+
output: rec.output ?? '',
|
|
618
|
+
envelope: rec.envelope === undefined ? null : rec.envelope,
|
|
619
|
+
});
|
|
620
|
+
imported += 1;
|
|
621
|
+
} catch (e) {
|
|
622
|
+
rejected.push({ index, error: e instanceof Error ? e.message : String(e) });
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
return { ok: true, imported, alreadyImported, rejected };
|
|
626
|
+
};
|
|
627
|
+
|
|
628
|
+
const prev = importChains.get(cwd) || Promise.resolve();
|
|
629
|
+
const next = prev.catch(() => {}).then(work);
|
|
630
|
+
importChains.set(cwd, next);
|
|
631
|
+
try {
|
|
632
|
+
sendJson(res, 200, await next);
|
|
633
|
+
} catch (e) {
|
|
634
|
+
sendJson(res, 500, { ok: false, error: 'import_failed', details: e instanceof Error ? e.message : String(e) });
|
|
635
|
+
} finally {
|
|
636
|
+
if (importChains.get(cwd) === next) importChains.delete(cwd);
|
|
637
|
+
}
|
|
638
|
+
});
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
module.exports = { registerAdminRoute, MAX_BODY_BYTES, MAX_IMPORT_BODY_BYTES, TASK_FIELDS, IMPORT_STATUSES };
|