@xiangyixie/dsh-superagent 0.12.0 → 0.12.1
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/CHANGELOG.md +12 -0
- package/README.md +3 -3
- package/bin/archive.js +185 -185
- package/bin/doctor.js +84 -84
- package/bin/sync.js +187 -187
- package/bin/workbench.js +98 -98
- package/lib/audit.js +555 -555
- package/lib/cost.js +267 -267
- package/lib/doctor.js +878 -878
- package/lib/guard.js +841 -841
- package/lib/index.js +2031 -2031
- package/lib/inject.js +138 -138
- package/lib/ledger.js +270 -270
- package/lib/memory.js +736 -736
- package/lib/orchestrator.js +3851 -3851
- package/lib/policy.js +739 -739
- package/lib/report.js +1068 -1068
- package/lib/store.js +873 -873
- package/lib/sync.js +456 -456
- package/lib/templates.js +690 -690
- package/lib/watch.js +810 -810
- package/lib/workbench.js +1119 -1119
- package/lib/workspace.js +433 -433
- package/package.json +1 -1
package/lib/index.js
CHANGED
|
@@ -1,2031 +1,2031 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* dsh-superagent — long-horizon autonomous runs for DeepSeek Harness.
|
|
3
|
-
*
|
|
4
|
-
* One goal enters; a planner decomposes it into subtasks; independent subtasks
|
|
5
|
-
* run in parallel child agents while a declared dependency holds the rest back;
|
|
6
|
-
* an aggregator merges their reports. Runs survive a host restart, can be
|
|
7
|
-
* cancelled, and have their token usage read back from the child sessions'
|
|
8
|
-
* durable logs.
|
|
9
|
-
*
|
|
10
|
-
* Registered tools: superagent_start, superagent_status, superagent_list,
|
|
11
|
-
* superagent_cancel, superagent_resume, superagent_followup, superagent_inject,
|
|
12
|
-
* superagent_answer, superagent_memory, superagent_template, superagent_audit.
|
|
13
|
-
*
|
|
14
|
-
* @module dsh-superagent
|
|
15
|
-
*/
|
|
16
|
-
import { randomUUID } from 'node:crypto'
|
|
17
|
-
import { existsSync } from 'node:fs'
|
|
18
|
-
import os from 'node:os'
|
|
19
|
-
import path from 'node:path'
|
|
20
|
-
import { fileURLToPath } from 'node:url'
|
|
21
|
-
import pkg from '../package.json' with { type: 'json' }
|
|
22
|
-
import { createAuditor } from './audit.js'
|
|
23
|
-
import { createOrchestrator, followupEffect } from './orchestrator.js'
|
|
24
|
-
import { createChildSteerer, createChildWatcher, INJECT_POLL_MS, pendingIds } from './inject.js'
|
|
25
|
-
import { createControlPlane } from './control.js'
|
|
26
|
-
import { formatMoney } from './cost.js'
|
|
27
|
-
import { createGuard } from './guard.js'
|
|
28
|
-
import { classifyError, describeError, summarizeError } from './errors.js'
|
|
29
|
-
import { createLedger } from './ledger.js'
|
|
30
|
-
import { createMemory, isInside, MEMORY_KINDS, normalizeScope } from './memory.js'
|
|
31
|
-
import { createNotifyPolicy, createOutbox } from './notify.js'
|
|
32
|
-
import { ACTIVE_STATUSES, createStore, resolveStateRoot, TERMINAL_STATUSES } from './store.js'
|
|
33
|
-
import { createTemplateStore, expandTemplate, formatTemplateDetail, formatTemplateList, TemplateError } from './templates.js'
|
|
34
|
-
import { createUsageReader } from './usage.js'
|
|
35
|
-
import { describeWorkspace } from './workspace.js'
|
|
36
|
-
import { createRunChangeTracker, createWorkbench } from './workbench.js'
|
|
37
|
-
|
|
38
|
-
export const name = 'dsh-superagent'
|
|
39
|
-
// The host menu and sessions are required. `subagents` is read through
|
|
40
|
-
// `ctx.get('subagents')`, so a profile without it still mounts the eleven tools;
|
|
41
|
-
// they then report what is missing instead of the plugin silently vanishing.
|
|
42
|
-
export const inject = ['tools', 'agents']
|
|
43
|
-
|
|
44
|
-
const DEFAULTS = {
|
|
45
|
-
/** Directory for run state; defaults to `$DSH_HOME/state/superagent`. */
|
|
46
|
-
stateDir: null,
|
|
47
|
-
/** Child backend registered on `ctx.subagents`. */
|
|
48
|
-
provider: 'spawn',
|
|
49
|
-
/** Optional provider override for every child agent; unset inherits the parent's model route. */
|
|
50
|
-
childProvider: null,
|
|
51
|
-
/** Optional model override for every child agent; unset inherits the parent's model. */
|
|
52
|
-
childModel: null,
|
|
53
|
-
/**
|
|
54
|
-
* Optional agent preset for child agents. A preset owns the child's tool
|
|
55
|
-
* composition, which is the only way this host version can restrict it.
|
|
56
|
-
*/
|
|
57
|
-
childPreset: null,
|
|
58
|
-
/**
|
|
59
|
-
* Delegation depth granted to child agents. 1 means a worker may not create
|
|
60
|
-
* children of its own; `provider-managed` leaves the cap to the backend.
|
|
61
|
-
*/
|
|
62
|
-
maxSubagentDepth: 1,
|
|
63
|
-
/** Upper bound on planned subtasks per run. */
|
|
64
|
-
maxSubtasks: 8,
|
|
65
|
-
/** Upper bound on subtasks executing at once. */
|
|
66
|
-
maxParallel: 3,
|
|
67
|
-
/** Runs allowed to be active at the same time; a start over this waits instead of failing. */
|
|
68
|
-
maxActiveRuns: 2,
|
|
69
|
-
/** Runs allowed to wait for a free slot when queueing is on; 0 disables queueing. */
|
|
70
|
-
maxQueuedRuns: 5,
|
|
71
|
-
/** How long a queued run waits before it fails, in minutes. */
|
|
72
|
-
queueTimeoutMinutes: 30,
|
|
73
|
-
/**
|
|
74
|
-
* Queue starts that did not ask for it with `queue: true`. Off by default: a
|
|
75
|
-
* caller opts in, so a script that relied on the quota error keeps seeing it.
|
|
76
|
-
*/
|
|
77
|
-
queueOnFull: false,
|
|
78
|
-
/** Attempts per subtask before it is marked failed. */
|
|
79
|
-
attempts: 2,
|
|
80
|
-
/** Wall-clock budget for a whole run, in minutes. */
|
|
81
|
-
deadlineMinutes: 120,
|
|
82
|
-
/** Hard cap on child model calls per run; 0 disables the cap. */
|
|
83
|
-
maxModelCallsPerRun: 80,
|
|
84
|
-
/** Hard cap on prompt + completion tokens per run; 0 disables the cap. */
|
|
85
|
-
maxTokensPerRun: 2_000_000,
|
|
86
|
-
/**
|
|
87
|
-
* List prices per 1M tokens, keyed by model id as it appears in usage logs.
|
|
88
|
-
* Only models listed here are priced; everything else is reported as unpriced
|
|
89
|
-
* rather than guessed. Nothing is shipped: a stale price is worse than none.
|
|
90
|
-
*/
|
|
91
|
-
pricing: {},
|
|
92
|
-
/** Bytes kept from one subtask report. */
|
|
93
|
-
resultCapBytes: 32 * 1024,
|
|
94
|
-
/** Write one message back to the owning session when a run finishes unattended. */
|
|
95
|
-
notifyOnComplete: true,
|
|
96
|
-
/**
|
|
97
|
-
* Proactive messages allowed per rolling hour. Runs that finish after the cap
|
|
98
|
-
* are folded into one summary instead of waking the session again.
|
|
99
|
-
*/
|
|
100
|
-
maxNotificationsPerHour: 3,
|
|
101
|
-
/**
|
|
102
|
-
* Extra rounds that retry failed subtasks before the failure is reported, so
|
|
103
|
-
* a transient error is healed automatically instead of asking the user.
|
|
104
|
-
*/
|
|
105
|
-
autoResumeRounds: 1,
|
|
106
|
-
/**
|
|
107
|
-
* Delivery attempts for one wake-up. A followup can fail while the session
|
|
108
|
-
* loop is busy; retrying it is the difference between a lost result and a
|
|
109
|
-
* late one. 0 means one attempt.
|
|
110
|
-
*/
|
|
111
|
-
notifyRetries: 2,
|
|
112
|
-
/** First delay between delivery attempts; it doubles per attempt. */
|
|
113
|
-
notifyRetryDelayMs: 2000,
|
|
114
|
-
/**
|
|
115
|
-
* Poll period, in milliseconds, used to observe when a running child claims
|
|
116
|
-
* an injected message. It is the resolution of every reported latency, so it
|
|
117
|
-
* is deliberately visible instead of rounded away.
|
|
118
|
-
*/
|
|
119
|
-
injectPollMs: INJECT_POLL_MS,
|
|
120
|
-
/**
|
|
121
|
-
* Child model used on a self-heal round when the failure looks transient
|
|
122
|
-
* (quota, rate limit, timeout). `null` keeps the configured route.
|
|
123
|
-
*/
|
|
124
|
-
childModelFallback: null,
|
|
125
|
-
/**
|
|
126
|
-
* Cross-run notebook. Notes live under `stateDir` and never enter the package
|
|
127
|
-
* or a default commit; see the privacy section of the README.
|
|
128
|
-
*/
|
|
129
|
-
memory: true,
|
|
130
|
-
/** Notebook scope; each scope is one file, so unrelated projects stay apart. */
|
|
131
|
-
memoryScope: 'default',
|
|
132
|
-
/** Notes kept before the notebook is compacted. */
|
|
133
|
-
memoryMaxEntries: 60,
|
|
134
|
-
/** Notes older than this are ignored, then compacted away. */
|
|
135
|
-
memoryMaxAgeDays: 30,
|
|
136
|
-
/** Notes injected into the planner and aggregator prompts. */
|
|
137
|
-
memoryDigestEntries: 12,
|
|
138
|
-
/** Character budget for the note part of that prompt context. */
|
|
139
|
-
memoryDigestChars: 1600,
|
|
140
|
-
/** Delete terminal runs older than this many days on mount; 0 keeps everything. */
|
|
141
|
-
keepRuns: 0,
|
|
142
|
-
/**
|
|
143
|
-
* Safety guard for child tool calls. Workers inherit the session's filesystem
|
|
144
|
-
* and credentials, so this policy is enforced on the host's tool pipeline.
|
|
145
|
-
* Defaults stand in `lib/guard.js`; see “Safety guard” in the README.
|
|
146
|
-
*/
|
|
147
|
-
guard: {
|
|
148
|
-
enabled: true,
|
|
149
|
-
/** Extra writable roots; the child session workspace and OS temp dir are implicit. */
|
|
150
|
-
allowWriteRoots: [],
|
|
151
|
-
/** Extra paths denied for both reading and writing. */
|
|
152
|
-
denyPaths: [],
|
|
153
|
-
/** Extra `{ id, pattern, reason }` command denials. */
|
|
154
|
-
denyCommands: [],
|
|
155
|
-
/** `{ id, pattern, reason }` entries that override a denial; every use is recorded. */
|
|
156
|
-
allowCommands: [],
|
|
157
|
-
/** Events kept per run; the counters still include events beyond the cap. */
|
|
158
|
-
maxEvents: 50,
|
|
159
|
-
},
|
|
160
|
-
/**
|
|
161
|
-
* Append-only audit trail under `<stateDir>/audit/audit.jsonl`. It is an
|
|
162
|
-
* observer layer: turning it off removes the trail, never the run behaviour.
|
|
163
|
-
*/
|
|
164
|
-
audit: true,
|
|
165
|
-
/**
|
|
166
|
-
* Permission policy for runs. Unset means `<stateDir>/policy.json` when that
|
|
167
|
-
* file exists, so dropping a policy next to the state is enough to enable it.
|
|
168
|
-
* An empty state means "no policy", which is exactly the old behaviour.
|
|
169
|
-
*/
|
|
170
|
-
policyFile: null,
|
|
171
|
-
/** Where the audit JSONL lives; defaults to `<stateDir>/audit`. */
|
|
172
|
-
auditDir: null,
|
|
173
|
-
/**
|
|
174
|
-
* Loopback HTTP port for the embedding surface. `null` (default) keeps the
|
|
175
|
-
* socket closed; `0` asks the OS for a free port. The bound address and its
|
|
176
|
-
* bearer token are written to `<stateDir>/control.json`.
|
|
177
|
-
*/
|
|
178
|
-
controlPort: null,
|
|
179
|
-
/**
|
|
180
|
-
* Run every worker in its own git worktree of `workspaceRoot`, so parallel
|
|
181
|
-
* workers cannot overwrite each other's files. Off by default: it needs a
|
|
182
|
-
* git repository and it moves files, which is not something a plugin should
|
|
183
|
-
* start doing unasked.
|
|
184
|
-
*/
|
|
185
|
-
workspaceIsolation: false,
|
|
186
|
-
/** Repository whose worktrees isolate the workers; defaults to the host's cwd. */
|
|
187
|
-
workspaceRoot: null,
|
|
188
|
-
/**
|
|
189
|
-
* Loopback HTTP port for the local workspace panel. `null` (default) keeps it
|
|
190
|
-
* off; `0` asks the OS for a free port. The bound address and its one-time
|
|
191
|
-
* token are written to `<stateDir>/workbench.json`.
|
|
192
|
-
*/
|
|
193
|
-
workbenchPort: null,
|
|
194
|
-
/**
|
|
195
|
-
* Directory the panel may read and edit. Everything outside it is refused.
|
|
196
|
-
* Defaults to the host process's working directory.
|
|
197
|
-
*/
|
|
198
|
-
workbenchRoot: null,
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
const REPORT_PREVIEW_CHARS = 8000
|
|
202
|
-
|
|
203
|
-
/**
|
|
204
|
-
* Coerce one numeric setting into its documented range. A value like "abc"
|
|
205
|
-
* would otherwise become NaN and silently remove a limit (NaN comparisons are
|
|
206
|
-
* always false), which is how a quota disappears without any error.
|
|
207
|
-
*/
|
|
208
|
-
function bounded(value, fallback, min, max) {
|
|
209
|
-
const number = Number(value)
|
|
210
|
-
if (!Number.isFinite(number)) return fallback
|
|
211
|
-
return Math.min(max, Math.max(min, Math.trunc(number)))
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
/**
|
|
215
|
-
* A port is a whole number in 0–65535, or nothing. A malformed value must not
|
|
216
|
-
* silently open a socket somewhere unexpected, so anything else stays off.
|
|
217
|
-
*/
|
|
218
|
-
function controlPortOf(value) {
|
|
219
|
-
if (value === null || value === undefined || value === false) return null
|
|
220
|
-
// Coercion would turn "" and " " into 0, i.e. an accidental listener; only a
|
|
221
|
-
// real number or a plain digit string may enable the surface.
|
|
222
|
-
if (typeof value === 'number') {
|
|
223
|
-
return Number.isInteger(value) && value >= 0 && value <= 65535 ? value : null
|
|
224
|
-
}
|
|
225
|
-
if (typeof value === 'string' && /^\d+$/.test(value.trim())) {
|
|
226
|
-
const number = Number(value.trim())
|
|
227
|
-
return number <= 65535 ? number : null
|
|
228
|
-
}
|
|
229
|
-
return null
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
/** Read a YAML/JSON boolean without letting the string "false" mean true. */
|
|
233
|
-
function flag(value, fallback) {
|
|
234
|
-
if (value === undefined) return fallback
|
|
235
|
-
if (typeof value === 'string') return !/^(false|0|off|no)$/i.test(value.trim())
|
|
236
|
-
return Boolean(value)
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
function resolveConfig(config) {
|
|
240
|
-
const merged = { ...DEFAULTS }
|
|
241
|
-
if (config && typeof config === 'object') {
|
|
242
|
-
for (const [key, value] of Object.entries(config)) {
|
|
243
|
-
if (value !== undefined) merged[key] = value
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
merged.maxSubtasks = bounded(merged.maxSubtasks, DEFAULTS.maxSubtasks, 1, 16)
|
|
247
|
-
merged.maxParallel = bounded(merged.maxParallel, DEFAULTS.maxParallel, 1, 8)
|
|
248
|
-
merged.maxActiveRuns = bounded(merged.maxActiveRuns, DEFAULTS.maxActiveRuns, 1, 8)
|
|
249
|
-
merged.maxQueuedRuns = bounded(merged.maxQueuedRuns, DEFAULTS.maxQueuedRuns, 0, 32)
|
|
250
|
-
merged.queueTimeoutMinutes = bounded(merged.queueTimeoutMinutes, DEFAULTS.queueTimeoutMinutes, 1, 720)
|
|
251
|
-
merged.queueOnFull = flag(merged.queueOnFull, DEFAULTS.queueOnFull)
|
|
252
|
-
merged.attempts = bounded(merged.attempts, DEFAULTS.attempts, 1, 5)
|
|
253
|
-
merged.deadlineMinutes = bounded(merged.deadlineMinutes, DEFAULTS.deadlineMinutes, 1, 720)
|
|
254
|
-
merged.maxModelCallsPerRun = bounded(merged.maxModelCallsPerRun, DEFAULTS.maxModelCallsPerRun, 0, 10000)
|
|
255
|
-
merged.maxTokensPerRun = bounded(merged.maxTokensPerRun, DEFAULTS.maxTokensPerRun, 0, 1e12)
|
|
256
|
-
merged.resultCapBytes = bounded(merged.resultCapBytes, DEFAULTS.resultCapBytes, 1024, 1024 * 1024)
|
|
257
|
-
merged.keepRuns = bounded(merged.keepRuns, DEFAULTS.keepRuns, 0, 3650)
|
|
258
|
-
merged.controlPort = controlPortOf(merged.controlPort)
|
|
259
|
-
merged.workbenchPort = controlPortOf(merged.workbenchPort)
|
|
260
|
-
merged.workbenchRoot = typeof merged.workbenchRoot === 'string' && merged.workbenchRoot.trim()
|
|
261
|
-
? merged.workbenchRoot.trim()
|
|
262
|
-
: null
|
|
263
|
-
merged.maxSubagentDepth = merged.maxSubagentDepth === 'provider-managed'
|
|
264
|
-
? 'provider-managed'
|
|
265
|
-
: bounded(merged.maxSubagentDepth, DEFAULTS.maxSubagentDepth, 0, 4)
|
|
266
|
-
// Per-model prices merge, so a user can add one route without restating the
|
|
267
|
-
// built-in table.
|
|
268
|
-
merged.pricing = { ...DEFAULTS.pricing, ...(config?.pricing ?? {}) }
|
|
269
|
-
merged.memory = flag(merged.memory, DEFAULTS.memory)
|
|
270
|
-
merged.audit = flag(merged.audit, DEFAULTS.audit)
|
|
271
|
-
merged.policyFile = typeof merged.policyFile === 'string' && merged.policyFile.trim()
|
|
272
|
-
? merged.policyFile.trim()
|
|
273
|
-
: null
|
|
274
|
-
merged.auditDir = typeof merged.auditDir === 'string' && merged.auditDir.trim()
|
|
275
|
-
? merged.auditDir.trim()
|
|
276
|
-
: null
|
|
277
|
-
merged.memoryScope = normalizeScope(merged.memoryScope)
|
|
278
|
-
merged.memoryMaxEntries = bounded(merged.memoryMaxEntries, DEFAULTS.memoryMaxEntries, 1, 500)
|
|
279
|
-
merged.memoryMaxAgeDays = bounded(merged.memoryMaxAgeDays, DEFAULTS.memoryMaxAgeDays, 1, 3650)
|
|
280
|
-
merged.memoryDigestEntries = bounded(merged.memoryDigestEntries, DEFAULTS.memoryDigestEntries, 1, 50)
|
|
281
|
-
merged.memoryDigestChars = bounded(merged.memoryDigestChars, DEFAULTS.memoryDigestChars, 200, 8000)
|
|
282
|
-
merged.autoResumeRounds = bounded(merged.autoResumeRounds, DEFAULTS.autoResumeRounds, 0, 3)
|
|
283
|
-
merged.notifyRetries = bounded(merged.notifyRetries, DEFAULTS.notifyRetries, 0, 5)
|
|
284
|
-
merged.notifyRetryDelayMs = bounded(merged.notifyRetryDelayMs, DEFAULTS.notifyRetryDelayMs, 0, 60000)
|
|
285
|
-
merged.injectPollMs = bounded(merged.injectPollMs, DEFAULTS.injectPollMs, 10, 1000)
|
|
286
|
-
merged.maxNotificationsPerHour = bounded(merged.maxNotificationsPerHour, DEFAULTS.maxNotificationsPerHour, 0, 1000)
|
|
287
|
-
merged.childModelFallback = typeof merged.childModelFallback === 'string' && merged.childModelFallback.trim()
|
|
288
|
-
? merged.childModelFallback.trim()
|
|
289
|
-
: null
|
|
290
|
-
merged.workspaceIsolation = flag(merged.workspaceIsolation, DEFAULTS.workspaceIsolation)
|
|
291
|
-
// A blank path would resolve to the cwd, which is how isolation would silently
|
|
292
|
-
// point at the wrong repository; blank therefore means "use the default".
|
|
293
|
-
merged.workspaceRoot = typeof merged.workspaceRoot === 'string' && merged.workspaceRoot.trim()
|
|
294
|
-
? merged.workspaceRoot.trim()
|
|
295
|
-
: null
|
|
296
|
-
// The guard block merges so a user can set only `allowCommands` without
|
|
297
|
-
// restating the rest of the defaults.
|
|
298
|
-
merged.guard = {
|
|
299
|
-
...DEFAULTS.guard,
|
|
300
|
-
...(config?.guard && typeof config.guard === 'object' ? config.guard : {}),
|
|
301
|
-
}
|
|
302
|
-
return merged
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
function preview(text, limit = REPORT_PREVIEW_CHARS) {
|
|
306
|
-
if (typeof text !== 'string') return ''
|
|
307
|
-
if (text.length <= limit) return text
|
|
308
|
-
return `${text.slice(0, limit)}\n\n[report truncated to ${limit} characters; full text is in the run state file]`
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
function durationText(ms) {
|
|
312
|
-
const seconds = Math.max(0, ms / 1000)
|
|
313
|
-
if (seconds < 60) return `${seconds.toFixed(1)}s`
|
|
314
|
-
const minutes = Math.floor(seconds / 60)
|
|
315
|
-
return `${minutes}m ${Math.round(seconds - minutes * 60)}s`
|
|
316
|
-
}
|
|
317
|
-
|
|
318
|
-
function elapsed(run) {
|
|
319
|
-
const start = Date.parse(run.startedAt)
|
|
320
|
-
const end = run.finishedAt ? Date.parse(run.finishedAt) : Date.now()
|
|
321
|
-
if (!Number.isFinite(start) || !Number.isFinite(end)) return 'unknown'
|
|
322
|
-
const wall = Math.max(0, end - start)
|
|
323
|
-
const active = Number.isFinite(run.activeMs) ? run.activeMs : wall
|
|
324
|
-
// A resumed run can span hours of downtime. Reporting one number would make
|
|
325
|
-
// it look like the model worked all that time.
|
|
326
|
-
if (run.resumedAt && wall - active > 5000) {
|
|
327
|
-
return `${durationText(active)} running, ${durationText(wall)} since it was started (includes time stopped)`
|
|
328
|
-
}
|
|
329
|
-
return durationText(wall)
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
function usageLine(usage, status) {
|
|
333
|
-
if (!usage || !usage.modelCalls) {
|
|
334
|
-
if (ACTIVE_STATUSES.has(status)) {
|
|
335
|
-
return 'usage: accounting pending — token usage is read from child session logs while the run is in progress'
|
|
336
|
-
}
|
|
337
|
-
return 'usage: not recorded — no child session log was readable for this run '
|
|
338
|
-
+ '(usually a run created before usage tracking, or a sessions directory that moved); '
|
|
339
|
-
+ 'token and cost figures are unavailable'
|
|
340
|
-
}
|
|
341
|
-
const models = Object.entries(usage.models ?? {})
|
|
342
|
-
.map(([model, entry]) => `${model}: ${entry.calls} call(s) ${entry.inputTokens} in / ${entry.outputTokens} out`)
|
|
343
|
-
.join('; ')
|
|
344
|
-
const cached = usage.cacheReadTokens ? ` (+${usage.cacheReadTokens} prompt tokens served from cache)` : ''
|
|
345
|
-
return `usage: input ${usage.inputTokens}${cached}, output ${usage.outputTokens}, calls ${usage.modelCalls}`
|
|
346
|
-
+ (models ? ` (${models})` : '')
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
/**
|
|
350
|
-
* Cost line for one run. The number is an estimate from the configured list
|
|
351
|
-
* prices; models without a price are named instead of guessed so a user can
|
|
352
|
-
* always tell how much of the spend the figure covers.
|
|
353
|
-
*/
|
|
354
|
-
function costLine(run) {
|
|
355
|
-
if (!run.usage || !run.usage.modelCalls) return null
|
|
356
|
-
const models = Object.keys(run.usage.models ?? {})
|
|
357
|
-
const cost = run.cost
|
|
358
|
-
// An all-unpriced run has no priced line at all. Printing 0.0000 there would
|
|
359
|
-
// claim the run was free, which is the one thing an estimate must not do.
|
|
360
|
-
const priced = Boolean(cost) && Object.keys(cost.byModel ?? {}).length > 0
|
|
361
|
-
if (!priced) {
|
|
362
|
-
const named = cost?.unpriced?.length ? cost.unpriced.join(', ') : (models.join(', ') || 'this model')
|
|
363
|
-
return `cost: not computed — no price configured for ${named}; `
|
|
364
|
-
+ 'add a pricing entry in cordis.patch.yml to get an estimate'
|
|
365
|
-
}
|
|
366
|
-
const money = formatMoney(cost)
|
|
367
|
-
if (cost.complete) return `cost: ${money} (estimate; all models priced)`
|
|
368
|
-
return `cost: at least ${money} (estimate; no price for ${cost.unpriced.join(', ')})`
|
|
369
|
-
}
|
|
370
|
-
|
|
371
|
-
/** Spend for one subtask: measured when priced, explicit when not. */
|
|
372
|
-
function subtaskCostText(subtask) {
|
|
373
|
-
if (!subtask?.usage || !subtask.usage.modelCalls) return ''
|
|
374
|
-
const cost = subtask.cost
|
|
375
|
-
if (!cost || Object.keys(cost.byModel ?? {}).length === 0) {
|
|
376
|
-
const named = cost?.unpriced?.length ? ` (${cost.unpriced.join(', ')})` : ''
|
|
377
|
-
return `, cost unpriced${named}`
|
|
378
|
-
}
|
|
379
|
-
return `, ${formatMoney(cost)}${cost.complete ? '' : '+'}`
|
|
380
|
-
}
|
|
381
|
-
|
|
382
|
-
/** Render one run as text for a tool result. */
|
|
383
|
-
function formatRun(run, { includeReport = true } = {}) {
|
|
384
|
-
const completed = run.subtasks.filter(subtask => subtask.status === 'completed').length
|
|
385
|
-
const lines = [
|
|
386
|
-
`run ${run.id} — ${run.status}`,
|
|
387
|
-
`goal: ${run.goal}`,
|
|
388
|
-
`plan: ${run.plan?.mode ?? 'pending'}; subtasks ${completed}/${run.subtasks.length} completed; `
|
|
389
|
-
+ `max ${run.limits.maxParallel} in parallel; ${run.limits.attempts} attempt(s) each`,
|
|
390
|
-
`elapsed: ${elapsed(run)}`,
|
|
391
|
-
usageLine(run.usage, run.status),
|
|
392
|
-
]
|
|
393
|
-
if (run.queue?.waiting) {
|
|
394
|
-
lines.push(
|
|
395
|
-
`queue: waiting for a free slot — position ${run.queue.position} of ${run.queue.of}; `
|
|
396
|
-
+ 'it starts automatically when an active run finishes, does not count against maxActiveRuns while it waits, '
|
|
397
|
-
+ `and fails if no slot frees by ${run.queue.timeoutAt}`,
|
|
398
|
-
)
|
|
399
|
-
} else if (run.queue?.expired) {
|
|
400
|
-
lines.push(`queue: timed out after waiting ${run.queue.of > 0 ? `behind ${run.queue.of} run(s)` : 'for a slot'}; it never started`)
|
|
401
|
-
} else if (run.queue?.cancelled) {
|
|
402
|
-
lines.push('queue: cancelled while waiting for a slot; it never started')
|
|
403
|
-
}
|
|
404
|
-
const unreadable = Object.keys(run.counters?.unreadable ?? {}).length
|
|
405
|
-
if (unreadable > 0) {
|
|
406
|
-
lines.push(
|
|
407
|
-
`usage note: ${unreadable} child session log(s) could not be read, so the token figures above cover only `
|
|
408
|
-
+ 'the readable ones; the model-call budget counted those children as one call each instead of ignoring them',
|
|
409
|
-
)
|
|
410
|
-
}
|
|
411
|
-
const cost = costLine(run)
|
|
412
|
-
if (cost) lines.push(cost)
|
|
413
|
-
if (run.memory?.digest) {
|
|
414
|
-
lines.push(
|
|
415
|
-
`memory: ${run.memory.notes} note(s) and ${run.memory.runs} earlier run(s) carried into this run `
|
|
416
|
-
+ `(${run.memory.digestChars} chars)`,
|
|
417
|
-
)
|
|
418
|
-
}
|
|
419
|
-
if (run.guard && (run.guard.blocked > 0 || run.guard.allowed > 0)) {
|
|
420
|
-
const rules = Object.entries(run.guard.byRule ?? {})
|
|
421
|
-
.map(([rule, count]) => `${rule} ×${count}`)
|
|
422
|
-
.join(', ')
|
|
423
|
-
lines.push(
|
|
424
|
-
`guard: ${run.guard.blocked} tool call(s) blocked; ${run.guard.allowed} explicit allow(s) recorded`
|
|
425
|
-
+ (rules ? ` (${rules})` : ''),
|
|
426
|
-
)
|
|
427
|
-
for (const event of (run.guard.events ?? []).filter(item => item.decision === 'blocked').slice(0, 3)) {
|
|
428
|
-
const detail = String(event.detail ?? '').replace(/\s+/g, ' ').slice(0, 120)
|
|
429
|
-
lines.push(` blocked ${event.tool}${event.label ? ` (${event.label})` : ''}: ${detail} — ${event.rule}`)
|
|
430
|
-
}
|
|
431
|
-
}
|
|
432
|
-
if (run.attention?.issue) {
|
|
433
|
-
lines.push(`attention: ${run.attention.issue}`)
|
|
434
|
-
}
|
|
435
|
-
if (run.attention?.items?.length > 0) {
|
|
436
|
-
const items = run.attention.items
|
|
437
|
-
const idOf = item => item.id ?? `q${items.indexOf(item) + 1}`
|
|
438
|
-
const open = items.filter(item => !item.answer)
|
|
439
|
-
const first = open[0] ?? items[0]
|
|
440
|
-
if (open.length > 0) {
|
|
441
|
-
lines.push(`needs your decision: ${first.question}${first.source ? ` (from ${first.source})` : ''}`)
|
|
442
|
-
if (first.options?.length) lines.push(`options: ${first.options.join(' | ')}`)
|
|
443
|
-
if (first.reason) lines.push(`why: ${first.reason}`)
|
|
444
|
-
lines.push(`attention id: ${idOf(first)}`)
|
|
445
|
-
} else {
|
|
446
|
-
// Answering does not hide the question: the record shows what was decided.
|
|
447
|
-
lines.push(`answered [${idOf(first)}]: ${first.question} — ${first.answer}`)
|
|
448
|
-
}
|
|
449
|
-
if (open.length > 1) {
|
|
450
|
-
lines.push(`and ${open.length - 1} more open question(s): ${open.slice(1).map(idOf).join(', ')}`)
|
|
451
|
-
}
|
|
452
|
-
}
|
|
453
|
-
if (Array.isArray(run.followups) && run.followups.length > 0) {
|
|
454
|
-
const pending = run.followups.filter(entry => !entry.appliedAt)
|
|
455
|
-
const missed = pending.filter(entry => entry.missedAt)
|
|
456
|
-
const applied = run.followups.length - pending.length
|
|
457
|
-
if (applied > 0) {
|
|
458
|
-
const stages = [...new Set(run.followups.filter(entry => entry.appliedAt).map(entry => entry.appliedAtStage))]
|
|
459
|
-
lines.push(`instructions: ${applied} added during the run, applied at ${stages.join(' / ')}`)
|
|
460
|
-
}
|
|
461
|
-
if (pending.length > missed.length) {
|
|
462
|
-
lines.push(
|
|
463
|
-
`instructions: ${pending.length - missed.length} waiting; they take effect at ${followupEffect(run).detail}`,
|
|
464
|
-
)
|
|
465
|
-
}
|
|
466
|
-
if (missed.length > 0) {
|
|
467
|
-
lines.push(
|
|
468
|
-
`instructions: ${missed.length} never took effect — ${missed[0].missedReason ?? 'the run settled first'}`,
|
|
469
|
-
)
|
|
470
|
-
}
|
|
471
|
-
}
|
|
472
|
-
if (Array.isArray(run.injections) && run.injections.length > 0) {
|
|
473
|
-
const degraded = run.injections.filter(entry => entry.status === 'degraded')
|
|
474
|
-
const targets = run.injections.flatMap(entry => entry.targets ?? [])
|
|
475
|
-
const applied = targets.filter(target => target.status === 'applied')
|
|
476
|
-
const pending = targets.filter(target => target.status === 'pending')
|
|
477
|
-
const missed = targets.filter(target => target.status === 'missed' || target.status === 'failed')
|
|
478
|
-
const worst = run.injectionStats?.worstLatencyMs
|
|
479
|
-
if (applied.length > 0) {
|
|
480
|
-
lines.push(
|
|
481
|
-
`live injections: ${applied.length} reached a child's next step`
|
|
482
|
-
+ (Number.isFinite(worst) ? ` (worst measured ${worst} ms)` : ''),
|
|
483
|
-
)
|
|
484
|
-
}
|
|
485
|
-
if (pending.length > 0) {
|
|
486
|
-
lines.push(`live injections: ${pending.length} accepted and waiting for a child's next step boundary`)
|
|
487
|
-
}
|
|
488
|
-
if (missed.length > 0) {
|
|
489
|
-
lines.push(
|
|
490
|
-
`live injections: ${missed.length} never entered a prompt — `
|
|
491
|
-
+ `${missed[0].missedReason ?? missed[0].error ?? 'the child left first'}`,
|
|
492
|
-
)
|
|
493
|
-
}
|
|
494
|
-
if (degraded.length > 0) {
|
|
495
|
-
lines.push(
|
|
496
|
-
`live injections: ${degraded.length} could not be delivered live and were queued; they take effect at `
|
|
497
|
-
+ followupEffect(run).detail,
|
|
498
|
-
)
|
|
499
|
-
}
|
|
500
|
-
}
|
|
501
|
-
if (Array.isArray(run.milestones) && run.milestones.length > 0) {
|
|
502
|
-
// Times are UTC because the record is ISO; a status line is not a place to
|
|
503
|
-
// start guessing the reader's timezone.
|
|
504
|
-
lines.push(`milestones: ${run.milestones
|
|
505
|
-
.map(milestone => `${milestone.name}@${String(milestone.at ?? '').slice(11, 19)}`)
|
|
506
|
-
.join(' → ')}`)
|
|
507
|
-
}
|
|
508
|
-
lines.push(...describeWorkspace(run.workspace))
|
|
509
|
-
const reportArtifact = (run.artifacts ?? []).find(artifact => artifact?.kind === 'report')
|
|
510
|
-
if (reportArtifact?.path) lines.push(`report file: ${reportArtifact.path} (${reportArtifact.bytes} bytes)`)
|
|
511
|
-
else if (run.artifactError) lines.push(`report file: not written — ${run.artifactError}`)
|
|
512
|
-
if (run.deduped) {
|
|
513
|
-
lines.push(
|
|
514
|
-
'deduped: true — an active run with the same goal already exists, so this call joined it instead of starting '
|
|
515
|
-
+ 'a second one (pass allow_duplicate: true to start another)',
|
|
516
|
-
)
|
|
517
|
-
}
|
|
518
|
-
if (run.selfHeal?.retried) {
|
|
519
|
-
lines.push(
|
|
520
|
-
`self-heal: retried ${run.selfHeal.retried} failed subtask(s) in ${run.selfHeal.rounds} extra round(s); `
|
|
521
|
-
+ `${run.selfHeal.recovered} recovered` + (run.selfHeal.model ? ` (on ${run.selfHeal.model})` : ''),
|
|
522
|
-
)
|
|
523
|
-
}
|
|
524
|
-
if (run.memoryWrite?.written > 0) {
|
|
525
|
-
lines.push(`memory: wrote ${run.memoryWrite.written} note(s) for the next run`)
|
|
526
|
-
} else if (run.memoryWrite?.reason && /^(the memory block|write failed)/.test(run.memoryWrite.reason)) {
|
|
527
|
-
lines.push(`memory note not written: ${run.memoryWrite.reason}`)
|
|
528
|
-
}
|
|
529
|
-
if (run.resumedAt) lines.push(`resumed at: ${run.resumedAt}`)
|
|
530
|
-
if (run.reclaimed) lines.push(`reclaimed: ${run.reclaimed.basis}`)
|
|
531
|
-
if (run.status === 'interrupted' && run.error) {
|
|
532
|
-
// Not a failure: the host went away and the run is waiting to be resumed.
|
|
533
|
-
lines.push(`note: ${run.error}`)
|
|
534
|
-
} else if (run.status !== 'cancelled' && run.error) {
|
|
535
|
-
lines.push(`error: ${summarizeError(run.error)}`)
|
|
536
|
-
if (run.status === 'failed') lines.push(`hint: ${classifyError(run.error).hint}`)
|
|
537
|
-
}
|
|
538
|
-
if (notifyFailed(run)) {
|
|
539
|
-
lines.push(`notify: not delivered — ${run.notify.reason}`)
|
|
540
|
-
}
|
|
541
|
-
if (run.cancelPending) {
|
|
542
|
-
lines.push('cancel: requested, but the process running this run has not confirmed yet; check superagent_status again in a few seconds')
|
|
543
|
-
}
|
|
544
|
-
for (const subtask of run.subtasks) {
|
|
545
|
-
const tokens = subtask.usage
|
|
546
|
-
? ` ${subtask.usage.inputTokens} in / ${subtask.usage.outputTokens} out${subtaskCostText(subtask)}`
|
|
547
|
-
: ''
|
|
548
|
-
// A subtask waiting on a dependency is not running and not failed; saying
|
|
549
|
-
// which tasks it waits for is the difference between "stuck" and "queued".
|
|
550
|
-
const waiting = subtask.status === 'waiting' && subtask.waitingOn?.length > 0
|
|
551
|
-
? ` — waiting on ${subtask.waitingOn.join(', ')}`
|
|
552
|
-
: ''
|
|
553
|
-
const skipped = subtask.status === 'skipped' && subtask.skippedReason
|
|
554
|
-
? ` — skipped: ${subtask.skippedReason}`
|
|
555
|
-
: ''
|
|
556
|
-
const detail = skipped || (subtask.error ? ` — ${summarizeError(subtask.error)}` : '')
|
|
557
|
-
// A cancelled run never judged its unfinished subtasks, so calling them
|
|
558
|
-
// "pending" or "failed (attempts 0)" would misreport what happened.
|
|
559
|
-
const status = run.status === 'cancelled' && subtask.status !== 'completed'
|
|
560
|
-
? (subtask.attempts > 0 ? 'cancelled' : 'skipped')
|
|
561
|
-
: subtask.status
|
|
562
|
-
lines.push(` [${subtask.index}] ${status} (attempts ${subtask.attempts}) ${subtask.title}${tokens}${waiting}${detail}`)
|
|
563
|
-
}
|
|
564
|
-
const failed = run.subtasks.find(subtask => subtask.error)
|
|
565
|
-
if (failed) {
|
|
566
|
-
const hint = classifyError(failed.error).hint
|
|
567
|
-
if (classifyError(failed.error).id !== 'unclassified') lines.push('', `hint: ${hint}`)
|
|
568
|
-
}
|
|
569
|
-
if (includeReport && run.report) {
|
|
570
|
-
lines.push('', 'report:', '', preview(run.report))
|
|
571
|
-
}
|
|
572
|
-
const openQuestion = (run.attention?.items ?? []).find(item => !item.answer)
|
|
573
|
-
if (openQuestion) {
|
|
574
|
-
// The user can act on this line directly; the id is what makes the answer
|
|
575
|
-
// land on the question it belongs to.
|
|
576
|
-
lines.push('', `next: superagent_answer run_id="${run.id}" attention_id="${openQuestion.id ?? 'q1'}" answer="..."`)
|
|
577
|
-
}
|
|
578
|
-
if (!TERMINAL_STATUSES.has(run.status)) {
|
|
579
|
-
lines.push('', `next: superagent_status run_id="${run.id}" wait_seconds=120`)
|
|
580
|
-
} else if (run.status === 'interrupted') {
|
|
581
|
-
lines.push('', `next: superagent_resume run_id="${run.id}"`)
|
|
582
|
-
}
|
|
583
|
-
return lines.join('\n')
|
|
584
|
-
}
|
|
585
|
-
|
|
586
|
-
function formatBytes(bytes) {
|
|
587
|
-
if (bytes < 1024) return `${bytes} B`
|
|
588
|
-
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
|
|
589
|
-
return `${(bytes / 1024 / 1024).toFixed(1)} MB`
|
|
590
|
-
}
|
|
591
|
-
|
|
592
|
-
/**
|
|
593
|
-
* The reply for one live injection.
|
|
594
|
-
*
|
|
595
|
-
* The wording separates four states instead of collapsing them into "sent":
|
|
596
|
-
* accepted (the child's inbox holds the message), applied (a step boundary
|
|
597
|
-
* claimed it, with the measured delay), pending (still waiting for that
|
|
598
|
-
* boundary), and missed (the child left before it could read the message).
|
|
599
|
-
*
|
|
600
|
-
* @param {object} run - live run record.
|
|
601
|
-
* @param {object} entry - injection receipt.
|
|
602
|
-
* @param {object | null} degraded - queued-as-followup fallback, when the host has no live channel.
|
|
603
|
-
* @param {{ pollMs: number }} options - poll resolution used for the measurement.
|
|
604
|
-
* @returns {string} the tool reply.
|
|
605
|
-
*/
|
|
606
|
-
function formatInjectionReply(run, entry, degraded, { pollMs }) {
|
|
607
|
-
const targets = entry?.targets ?? []
|
|
608
|
-
const accepted = targets.filter(target => target.messageId)
|
|
609
|
-
const applied = targets.filter(target => target.status === 'applied')
|
|
610
|
-
const missed = targets.filter(target => target.status === 'missed')
|
|
611
|
-
const failed = targets.filter(target => target.status === 'failed')
|
|
612
|
-
const pending = targets.filter(target => target.status === 'pending')
|
|
613
|
-
const lines = []
|
|
614
|
-
|
|
615
|
-
if (degraded) {
|
|
616
|
-
lines.push(
|
|
617
|
-
`instruction ${entry.id} could not be delivered live on run ${run.id}: ${degraded.reason}`,
|
|
618
|
-
`it was queued as instruction ${degraded.followup.id} instead, and takes effect at ${degraded.effect.detail} `
|
|
619
|
-
+ `(boundary: ${degraded.effect.boundary}).`,
|
|
620
|
-
'a worker that is already running is not interrupted and does not see it.',
|
|
621
|
-
)
|
|
622
|
-
return lines.join('\n')
|
|
623
|
-
}
|
|
624
|
-
|
|
625
|
-
lines.push(
|
|
626
|
-
`instruction ${entry.id} accepted by ${accepted.length}/${targets.length} running worker(s) on run ${run.id} — `
|
|
627
|
-
+ `${run.status}`,
|
|
628
|
-
)
|
|
629
|
-
for (const target of targets) {
|
|
630
|
-
const who = `subtask ${target.subtaskIndex} (child ${target.childId})`
|
|
631
|
-
if (target.status === 'applied') {
|
|
632
|
-
lines.push(` ${who}: seen at the child's next step after ${target.latencyMs ?? '?'} ms${target.via ? ` via ${target.via}` : ''}`)
|
|
633
|
-
} else if (target.status === 'pending') {
|
|
634
|
-
lines.push(` ${who}: accepted (message ${target.messageId}); it has not reached a step boundary yet`)
|
|
635
|
-
} else if (target.status === 'missed') {
|
|
636
|
-
lines.push(` ${who}: missed — ${target.missedReason}`)
|
|
637
|
-
} else {
|
|
638
|
-
lines.push(` ${who}: not delivered — ${target.error ?? 'unknown error'}`)
|
|
639
|
-
}
|
|
640
|
-
}
|
|
641
|
-
const stats = run.injectionStats
|
|
642
|
-
const worst = Number.isFinite(stats?.worstLatencyMs) ? `${stats.worstLatencyMs} ms` : 'not measured yet'
|
|
643
|
-
lines.push(
|
|
644
|
-
'delivery: steering is read at the child\'s next step boundary, just before its next model request. It does not '
|
|
645
|
-
+ 'interrupt a model call already in flight, so the worst case is the remainder of that step (its model response '
|
|
646
|
-
+ 'plus tool batch).',
|
|
647
|
-
`measured on this run: worst ${worst} over ${stats?.samples ?? 0} claimed message(s); the poll resolution is `
|
|
648
|
-
+ `${pollMs} ms.`,
|
|
649
|
-
)
|
|
650
|
-
if (pending.length > 0) {
|
|
651
|
-
lines.push(
|
|
652
|
-
`not seen yet: ${pending.length} message(s) are still waiting at a live child's boundary; this reply does not `
|
|
653
|
-
+ 'claim they were read. superagent_status shows the receipt once the boundary claims it.',
|
|
654
|
-
)
|
|
655
|
-
}
|
|
656
|
-
if (missed.length + failed.length > 0) {
|
|
657
|
-
lines.push(
|
|
658
|
-
`${missed.length + failed.length} message(s) never entered a prompt. If the work must still change, send the `
|
|
659
|
-
+ 'instruction again to a running worker, or use superagent_followup for the next prompt.',
|
|
660
|
-
)
|
|
661
|
-
}
|
|
662
|
-
lines.push('', formatRun(run, { includeReport: false }))
|
|
663
|
-
return lines.join('\n')
|
|
664
|
-
}
|
|
665
|
-
|
|
666
|
-
/** True when a run finished but its owner was never told, and that is a problem. */
|
|
667
|
-
function notifyFailed(run) {
|
|
668
|
-
if (!run.notify || run.notify.delivered) return false
|
|
669
|
-
return !/^(skipped|disabled):/.test(String(run.notify.reason ?? ''))
|
|
670
|
-
}
|
|
671
|
-
|
|
672
|
-
/** What a failed run already tried, so the message is not just "it broke". */
|
|
673
|
-
function triedLine(run) {
|
|
674
|
-
const attempts = run.limits?.attempts ?? 1
|
|
675
|
-
const parts = [`tried: ${attempts} attempt(s) per subtask`]
|
|
676
|
-
if (run.selfHeal?.rounds > 0) {
|
|
677
|
-
parts.push(`${run.selfHeal.rounds} self-heal round(s), ${run.selfHeal.recovered ?? 0} recovered`)
|
|
678
|
-
}
|
|
679
|
-
if (run.selfHeal?.model) parts.push(`switched to ${run.selfHeal.model} for the retry`)
|
|
680
|
-
return `${parts.join('; ')}.`
|
|
681
|
-
}
|
|
682
|
-
|
|
683
|
-
function formatList(runs, limit, stats = null) {
|
|
684
|
-
if (runs.length === 0) return 'no superagent runs recorded'
|
|
685
|
-
const rows = runs.slice(0, limit).map(run => {
|
|
686
|
-
const completed = run.subtasks.filter(subtask => subtask.status === 'completed').length
|
|
687
|
-
return `${run.id} ${run.status.padEnd(11)} ${completed}/${run.subtasks.length} done `
|
|
688
|
-
+ `${run.goal.slice(0, 70)}${notifyFailed(run) ? ' (result not delivered to the session)' : ''}`
|
|
689
|
-
})
|
|
690
|
-
const lines = [`${runs.length} run(s):`, ...rows]
|
|
691
|
-
if (stats) {
|
|
692
|
-
lines.push('', `state: ${stats.files} file(s), ${formatBytes(stats.bytes)} in ${stats.root}`
|
|
693
|
-
+ (stats.corrupt ? ` (${stats.corrupt} quarantined file(s))` : ''))
|
|
694
|
-
if (stats.memory) {
|
|
695
|
-
lines.push(`memory: ${stats.memory.entries} note(s), ${formatBytes(stats.memory.bytes)} in ${path.dirname(stats.memory.path)}`)
|
|
696
|
-
}
|
|
697
|
-
if (stats.pendingNotifications > 0) {
|
|
698
|
-
lines.push(`notifications: ${stats.pendingNotifications} run(s) held back by the hourly limit; `
|
|
699
|
-
+ 'they are folded into the next message')
|
|
700
|
-
}
|
|
701
|
-
if (stats.ledger) {
|
|
702
|
-
const ledger = stats.ledger
|
|
703
|
-
if (ledger.runs === 0) {
|
|
704
|
-
lines.push(`ledger: no spend recorded in the last ${stats.ledgerDays} days`)
|
|
705
|
-
} else if (ledger.priced === 0) {
|
|
706
|
-
lines.push(`ledger: ${ledger.runs} run(s) in the last ${stats.ledgerDays} days are unpriced — `
|
|
707
|
-
+ 'no configured price matches their models, so no total is claimed')
|
|
708
|
-
} else {
|
|
709
|
-
const total = ledger.mixedCurrency
|
|
710
|
-
? `${formatMoney({ totalMicros: ledger.totalMicros, currency: ledger.currency ?? 'USD' })}`
|
|
711
|
-
: formatMoney({ totalMicros: ledger.totalMicros, currency: ledger.currency })
|
|
712
|
-
lines.push(`ledger: ${total} across ${ledger.priced} priced run(s) in the last ${stats.ledgerDays} days`
|
|
713
|
-
+ (ledger.unpricedRuns > 0 ? ` (${ledger.unpricedRuns} run(s) partially unpriced)` : '')
|
|
714
|
-
+ (ledger.mixedCurrency ? ' (mixed currencies; figure uses the first)' : ''))
|
|
715
|
-
}
|
|
716
|
-
}
|
|
717
|
-
}
|
|
718
|
-
return lines.join('\n')
|
|
719
|
-
}
|
|
720
|
-
|
|
721
|
-
function toolText(text) {
|
|
722
|
-
return [{ type: 'text', text }]
|
|
723
|
-
}
|
|
724
|
-
|
|
725
|
-
/**
|
|
726
|
-
* Render one audit query as a short report: the window, how the events break
|
|
727
|
-
* down, and the latest rows. The full detail stays one export away, so this
|
|
728
|
-
* never floods the session with a thousand lines it cannot use.
|
|
729
|
-
*/
|
|
730
|
-
function formatAudit(result, { limit = 8 } = {}) {
|
|
731
|
-
const { events, scanned, invalid, torn, file } = result
|
|
732
|
-
const notes = []
|
|
733
|
-
if (invalid) notes.push(`${invalid} unreadable line(s) skipped`)
|
|
734
|
-
if (torn) notes.push('1 torn trailing line ignored')
|
|
735
|
-
const tail = notes.length > 0 ? `; ${notes.join('; ')}` : ''
|
|
736
|
-
if (events.length === 0) return `audit: no matching events (${scanned} scanned in ${file}${tail})`
|
|
737
|
-
const tally = field => {
|
|
738
|
-
const counts = new Map()
|
|
739
|
-
for (const event of events) {
|
|
740
|
-
const key = event[field] ?? 'none'
|
|
741
|
-
counts.set(key, (counts.get(key) ?? 0) + 1)
|
|
742
|
-
}
|
|
743
|
-
return [...counts.entries()]
|
|
744
|
-
.sort((a, b) => b[1] - a[1])
|
|
745
|
-
.map(([key, count]) => `${key} ${count}`)
|
|
746
|
-
.join(', ')
|
|
747
|
-
}
|
|
748
|
-
const lines = [
|
|
749
|
-
`audit: ${events.length} event(s) match (${scanned} scanned in ${file}${tail})`,
|
|
750
|
-
`window: ${events[0].at} .. ${events.at(-1).at}`,
|
|
751
|
-
`decision: ${tally('decision')}`,
|
|
752
|
-
`kind: ${tally('kind')}`,
|
|
753
|
-
`result: ${tally('result')}`,
|
|
754
|
-
'latest:',
|
|
755
|
-
]
|
|
756
|
-
for (const event of events.slice(-Math.max(1, limit))) {
|
|
757
|
-
lines.push(
|
|
758
|
-
` ${event.at} ${String(event.decision ?? '-').padEnd(7)} ${String(event.kind).padEnd(12)} `
|
|
759
|
-
+ `${String(event.runId ?? '-').padEnd(14)} ${event.rule ?? '-'} ${event.target ?? ''}`.trimEnd(),
|
|
760
|
-
)
|
|
761
|
-
}
|
|
762
|
-
return lines.join('\n')
|
|
763
|
-
}
|
|
764
|
-
|
|
765
|
-
function defineTool(spec) {
|
|
766
|
-
return {
|
|
767
|
-
name: spec.name,
|
|
768
|
-
description: spec.description,
|
|
769
|
-
parameters: { type: 'object', properties: spec.properties, ...(spec.required?.length ? { required: spec.required } : {}) },
|
|
770
|
-
output: { schema: { type: 'string' }, render: (_args, value) => toolText(value) },
|
|
771
|
-
execute: spec.execute,
|
|
772
|
-
}
|
|
773
|
-
}
|
|
774
|
-
|
|
775
|
-
/**
|
|
776
|
-
* Mount the plugin.
|
|
777
|
-
* @param {object} ctx - Cordis context.
|
|
778
|
-
* @param {object} [config] - row config from `cordis.patch.yml`.
|
|
779
|
-
*/
|
|
780
|
-
export function apply(ctx, config) {
|
|
781
|
-
const log = message => console.error(`[dsh-superagent] ${message}`)
|
|
782
|
-
const configuredPort = config?.controlPort
|
|
783
|
-
const configuredWorkbenchPort = config?.workbenchPort
|
|
784
|
-
const cfg = resolveConfig(config)
|
|
785
|
-
if (configuredPort !== undefined && configuredPort !== null && cfg.controlPort === null) {
|
|
786
|
-
log(`controlPort ${JSON.stringify(configuredPort)} is not a whole number in 0–65535; the local HTTP control plane stays off`)
|
|
787
|
-
}
|
|
788
|
-
if (configuredWorkbenchPort !== undefined && configuredWorkbenchPort !== null && cfg.workbenchPort === null) {
|
|
789
|
-
log(`workbenchPort ${JSON.stringify(configuredWorkbenchPort)} is not a whole number in 0–65535; the workspace panel stays off`)
|
|
790
|
-
}
|
|
791
|
-
if (!ctx?.tools || typeof ctx.tools.register !== 'function') {
|
|
792
|
-
console.error('[dsh-superagent] host exposes no tools service; plugin disabled')
|
|
793
|
-
return
|
|
794
|
-
}
|
|
795
|
-
|
|
796
|
-
const baseStore = createStore(resolveStateRoot(cfg.stateDir), { warn: log })
|
|
797
|
-
const workbenchRoot = cfg.workbenchRoot ? path.resolve(cfg.workbenchRoot) : process.cwd()
|
|
798
|
-
// The panel reads `run.changes` from the durable record. The tracker writes
|
|
799
|
-
// that field through the same store the orchestrator already uses, so the
|
|
800
|
-
// orchestrator itself needs no edit and the panel can stay opt-in.
|
|
801
|
-
const changeTracker = cfg.workbenchPort === null
|
|
802
|
-
? null
|
|
803
|
-
: createRunChangeTracker({ store: baseStore, root: workbenchRoot, stateRoot: baseStore.root, warn: log })
|
|
804
|
-
const store = changeTracker?.store ?? baseStore
|
|
805
|
-
const home = process.env.DSH_HOME?.trim() || path.join(os.homedir(), '.dsh')
|
|
806
|
-
const readUsage = createUsageReader({ sessionsRoot: path.join(home, 'sessions'), warn: log })
|
|
807
|
-
// The ledger is an append-only history of priced runs. Writing it here, from
|
|
808
|
-
// the read paths, keeps it out of the scheduling loop: a status or list call
|
|
809
|
-
// is already a snapshot of finished work, and a run is recorded exactly once.
|
|
810
|
-
const ledger = createLedger(store.root, { warn: log })
|
|
811
|
-
const LEDGER_WINDOW_DAYS = 30
|
|
812
|
-
|
|
813
|
-
/** Append finished runs to the spend ledger; a ledger fault never blocks a tool. */
|
|
814
|
-
async function recordSpend(runs) {
|
|
815
|
-
for (const run of runs) {
|
|
816
|
-
try {
|
|
817
|
-
await ledger.record(run)
|
|
818
|
-
} catch (error) {
|
|
819
|
-
log(`ledger: cannot record run ${run?.id}: ${error?.message ?? error}`)
|
|
820
|
-
}
|
|
821
|
-
}
|
|
822
|
-
}
|
|
823
|
-
|
|
824
|
-
// A state directory inside the installed package would put the notebook in a
|
|
825
|
-
// directory that is meant to be shipped byte-for-byte from git. Refuse rather
|
|
826
|
-
// than rely on the `.gitignore` the notebook writes for itself.
|
|
827
|
-
const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
|
828
|
-
const memoryBlocked = isInside(store.root, packageRoot)
|
|
829
|
-
const memory = cfg.memory && !memoryBlocked ? createMemory(store.root, { warn: log }) : null
|
|
830
|
-
if (cfg.memory && memoryBlocked) {
|
|
831
|
-
log(`cross-run memory stays off: stateDir ${store.root} is inside the installed package; point stateDir elsewhere`)
|
|
832
|
-
}
|
|
833
|
-
// Built-ins need no storage; only custom templates touch the state directory,
|
|
834
|
-
// and a state directory inside the package must not receive new files.
|
|
835
|
-
const templates = createTemplateStore(store.root, { warn: log })
|
|
836
|
-
// The trail and its policy live beside the run state, so one directory holds
|
|
837
|
-
// everything a reviewer needs. A policy the user did not name is picked up
|
|
838
|
-
// only when it already exists; without one, runs behave exactly as before.
|
|
839
|
-
const auditDir = cfg.auditDir ? path.resolve(cfg.auditDir) : path.join(store.root, 'audit')
|
|
840
|
-
const implicitPolicy = path.join(store.root, 'policy.json')
|
|
841
|
-
const policyFile = cfg.policyFile
|
|
842
|
-
? path.resolve(cfg.policyFile)
|
|
843
|
-
: (existsSync(implicitPolicy) ? implicitPolicy : null)
|
|
844
|
-
const auditBlocked = isInside(auditDir, packageRoot)
|
|
845
|
-
const auditor = cfg.audit && !auditBlocked ? createAuditor({ dir: auditDir, policyFile, warn: log }) : null
|
|
846
|
-
if (cfg.audit && auditBlocked) {
|
|
847
|
-
log(`audit trail stays off: ${auditDir} is inside the installed package; point stateDir or auditDir elsewhere`)
|
|
848
|
-
}
|
|
849
|
-
if (auditor) {
|
|
850
|
-
auditor.policyError()
|
|
851
|
-
.then(error => {
|
|
852
|
-
if (error) log(error.message ?? String(error))
|
|
853
|
-
})
|
|
854
|
-
.catch(() => {})
|
|
855
|
-
log(`audit trail ${auditor.file}; policy ${policyFile ?? 'none (permissive)'}`)
|
|
856
|
-
}
|
|
857
|
-
|
|
858
|
-
// The guard is mounted on the host's tool pipeline, scoped to children this
|
|
859
|
-
// plugin spawns. `process.cwd()` is only a fallback: every call uses the
|
|
860
|
-
// child session's own workspace when the host exposes one.
|
|
861
|
-
const guard = createGuard({ config: cfg.guard, cwd: process.cwd(), warn: log })
|
|
862
|
-
if (guard.enabled) {
|
|
863
|
-
const enforce = exec => {
|
|
864
|
-
const verdict = guard.checkToolCall(exec)
|
|
865
|
-
if (!verdict.blocked) return undefined
|
|
866
|
-
log(`guard blocked ${exec?.name ?? 'tool'} for ${verdict.label ?? 'a worker'}: ${verdict.rule} — ${verdict.reason}`)
|
|
867
|
-
// A block is evidence, so it belongs in the same trail as every other
|
|
868
|
-
// decision. The guard owns the verdict; the trail only records it.
|
|
869
|
-
if (auditor && typeof auditor.record === 'function') {
|
|
870
|
-
auditor.record({
|
|
871
|
-
kind: 'blocked',
|
|
872
|
-
action: exec?.name ?? 'tool',
|
|
873
|
-
target: verdict.detail ?? null,
|
|
874
|
-
actor: verdict.label ?? null,
|
|
875
|
-
decision: 'deny',
|
|
876
|
-
result: 'blocked',
|
|
877
|
-
rule: verdict.rule ?? null,
|
|
878
|
-
source: 'guard',
|
|
879
|
-
meta: { reason: verdict.reason ?? null },
|
|
880
|
-
}).catch(error => log(`audit: cannot record guard block: ${error?.message ?? error}`))
|
|
881
|
-
}
|
|
882
|
-
return verdict.reasonText
|
|
883
|
-
}
|
|
884
|
-
let hooked = false
|
|
885
|
-
if (typeof ctx.tools.guard === 'function') {
|
|
886
|
-
const release = ctx.tools.guard(enforce)
|
|
887
|
-
hooked = true
|
|
888
|
-
if (typeof release === 'function' && typeof ctx.effect === 'function') {
|
|
889
|
-
ctx.effect(() => () => release())
|
|
890
|
-
}
|
|
891
|
-
} else if (typeof ctx.on === 'function') {
|
|
892
|
-
ctx.on('tools/pre-execute', async (exec, next) => {
|
|
893
|
-
const reason = enforce(exec)
|
|
894
|
-
return reason ? { kind: 'deny', reason } : next()
|
|
895
|
-
})
|
|
896
|
-
hooked = true
|
|
897
|
-
}
|
|
898
|
-
if (!hooked) {
|
|
899
|
-
log('guard is enabled but this host exposes neither tools.guard nor tools/pre-execute; child calls are not gated')
|
|
900
|
-
}
|
|
901
|
-
}
|
|
902
|
-
|
|
903
|
-
const notifyPolicy = createNotifyPolicy({
|
|
904
|
-
stateFile: path.join(store.root, 'notifications.json'),
|
|
905
|
-
maxPerHour: cfg.maxNotificationsPerHour,
|
|
906
|
-
warn: log,
|
|
907
|
-
})
|
|
908
|
-
// One wake-up per run, delivered in order per session. A busy session loop
|
|
909
|
-
// can reject a followup, so the same message is retried with backoff instead
|
|
910
|
-
// of being reported as lost on the first refusal.
|
|
911
|
-
const outbox = createOutbox({ retries: cfg.notifyRetries, delayMs: cfg.notifyRetryDelayMs })
|
|
912
|
-
|
|
913
|
-
/** Child sessions spawned by this process; a run may not be started from one. */
|
|
914
|
-
const childIds = new Set()
|
|
915
|
-
|
|
916
|
-
/**
|
|
917
|
-
* The subagent service is optional, so it is read from the service store at
|
|
918
|
-
* call time rather than declared as an injection: a profile without it must
|
|
919
|
-
* still mount the eleven tools (they then explain what is missing), and reading
|
|
920
|
-
* it lazily also sees a service that registers after this plugin.
|
|
921
|
-
*/
|
|
922
|
-
function getSubagents() {
|
|
923
|
-
if (typeof ctx.get === 'function') {
|
|
924
|
-
const service = ctx.get('subagents')
|
|
925
|
-
if (service) return service
|
|
926
|
-
}
|
|
927
|
-
// The direct property is topology-sensitive on a real host; it is only a
|
|
928
|
-
// fallback for test contexts that provide the service without a registry.
|
|
929
|
-
try {
|
|
930
|
-
return ctx.subagents
|
|
931
|
-
} catch {
|
|
932
|
-
return undefined
|
|
933
|
-
}
|
|
934
|
-
}
|
|
935
|
-
|
|
936
|
-
/** The agent registry, read lazily for the same reason as `subagents`. */
|
|
937
|
-
function getAgents() {
|
|
938
|
-
if (typeof ctx.get === 'function') {
|
|
939
|
-
const service = ctx.get('agents')
|
|
940
|
-
if (service) return service
|
|
941
|
-
}
|
|
942
|
-
return undefined
|
|
943
|
-
}
|
|
944
|
-
|
|
945
|
-
/** Remember a child id for the recursion guard without growing forever. */
|
|
946
|
-
function rememberChild(childId) {
|
|
947
|
-
if (!childId) return
|
|
948
|
-
childIds.add(childId)
|
|
949
|
-
if (childIds.size > 512) childIds.delete(childIds.values().next().value)
|
|
950
|
-
}
|
|
951
|
-
|
|
952
|
-
/**
|
|
953
|
-
* Map a run outcome to one message for the owning session.
|
|
954
|
-
*
|
|
955
|
-
* The notification policy decides first: a cancelled run is never announced,
|
|
956
|
-
* and a burst above the hourly cap is buffered instead of waking the session
|
|
957
|
-
* once per run. The followup is awaited: an unhandled rejection from it would
|
|
958
|
-
* otherwise escape as a host-level error while the run already claims it was
|
|
959
|
-
* delivered.
|
|
960
|
-
*/
|
|
961
|
-
async function notifyParent(run) {
|
|
962
|
-
if (run.notified) return { delivered: false, reason: 'skipped: the owning session was already notified' }
|
|
963
|
-
if (!cfg.notifyOnComplete) return { delivered: false, reason: 'disabled: notifyOnComplete is false' }
|
|
964
|
-
const agents = typeof ctx.get === 'function' ? ctx.get('agents') : undefined
|
|
965
|
-
const agent = agents && typeof agents.get === 'function' ? agents.get(run.parentSessionId) : undefined
|
|
966
|
-
if (!agent || typeof agent.followup !== 'function') {
|
|
967
|
-
log(`run ${run.id} finished but its session ${run.parentSessionId} is no longer live`)
|
|
968
|
-
return {
|
|
969
|
-
delivered: false,
|
|
970
|
-
reason: `the owning session ${run.parentSessionId} is no longer live; read the report with superagent_status`,
|
|
971
|
-
}
|
|
972
|
-
}
|
|
973
|
-
// Reserve only once the session is known to exist: a missing session is not
|
|
974
|
-
// an interruption and must not consume the hourly budget.
|
|
975
|
-
const verdict = await notifyPolicy.reserve(run)
|
|
976
|
-
if (!verdict.allowed) return { delivered: false, reason: verdict.reason }
|
|
977
|
-
|
|
978
|
-
const completed = run.subtasks.filter(subtask => subtask.status === 'completed').length
|
|
979
|
-
const decision = (run.attention?.items ?? []).find(item => !item.answer) ?? null
|
|
980
|
-
const questionId = decision?.id ?? (decision ? 'q1' : null)
|
|
981
|
-
const lines = decision
|
|
982
|
-
? [`[superagent] needs your decision on run ${run.id} (question ${questionId}): ${decision.question}`]
|
|
983
|
-
: [`[superagent] run ${run.id} finished: ${run.status} (${completed}/${run.subtasks.length} subtasks).`]
|
|
984
|
-
if (decision) {
|
|
985
|
-
if (decision.options?.length) lines.push(`Options: ${decision.options.join(' / ')}.`)
|
|
986
|
-
lines.push(`The run itself ended as ${run.status} (${completed}/${run.subtasks.length} subtasks).`)
|
|
987
|
-
lines.push(`Answer with superagent_answer attention_id="${questionId}".`)
|
|
988
|
-
} else if (run.attention?.issue) {
|
|
989
|
-
// A malformed block asked for a decision too; keeping it quiet would look
|
|
990
|
-
// like an ordinary finished run.
|
|
991
|
-
lines.push(`Attention: ${run.attention.issue}.`)
|
|
992
|
-
}
|
|
993
|
-
if (!decision && run.status !== 'completed') lines.push(triedLine(run))
|
|
994
|
-
if (run.workspace?.conflicts > 0) {
|
|
995
|
-
// A conflict is the one outcome the user must act on even when the run
|
|
996
|
-
// "completed": saying only "finished: completed" would bury it.
|
|
997
|
-
lines.push(
|
|
998
|
-
`${run.workspace.conflicts} worker branch(es) could not be merged into ${run.workspace.base}; `
|
|
999
|
-
+ 'both sides were kept, so nothing was lost — superagent_status lists the conflicting files and the branch '
|
|
1000
|
-
+ 'to merge by hand.',
|
|
1001
|
-
)
|
|
1002
|
-
} else if (run.workspace?.mode === 'unavailable') {
|
|
1003
|
-
lines.push(`Workspace isolation was unavailable (${run.workspace.reason}), so the workers shared one directory.`)
|
|
1004
|
-
}
|
|
1005
|
-
if (verdict.batch.length > 0) {
|
|
1006
|
-
lines.push(
|
|
1007
|
-
'Also finished since the last update: '
|
|
1008
|
-
+ `${verdict.batch.map(item => `${item.id} ${item.status}`).join('; ')}.`,
|
|
1009
|
-
)
|
|
1010
|
-
}
|
|
1011
|
-
lines.push(`Call superagent_status with run_id="${run.id}" to read the report.`)
|
|
1012
|
-
try {
|
|
1013
|
-
await outbox.enqueue(run.parentSessionId, () => agent.followup({
|
|
1014
|
-
id: randomUUID(),
|
|
1015
|
-
role: 'user',
|
|
1016
|
-
content: [{ type: 'text', text: lines.join(' ') }],
|
|
1017
|
-
source: { kind: 'user' },
|
|
1018
|
-
}))
|
|
1019
|
-
run.notified = true
|
|
1020
|
-
return { delivered: true }
|
|
1021
|
-
} catch (error) {
|
|
1022
|
-
log(`cannot notify session ${run.parentSessionId}: ${error?.message ?? error}`)
|
|
1023
|
-
// The folded runs were reserved but never delivered. Put them back so the
|
|
1024
|
-
// next allowed message still carries them, up to the policy's retry cap.
|
|
1025
|
-
await notifyPolicy.restore(verdict.batch).catch(restoreError => {
|
|
1026
|
-
log(`cannot restore ${verdict.batch.length} batched notification(s): ${restoreError?.message ?? restoreError}`)
|
|
1027
|
-
})
|
|
1028
|
-
return { delivered: false, reason: `waking the session failed: ${error?.message ?? error}` }
|
|
1029
|
-
}
|
|
1030
|
-
}
|
|
1031
|
-
|
|
1032
|
-
const orchestrator = createOrchestrator({
|
|
1033
|
-
store,
|
|
1034
|
-
config: cfg,
|
|
1035
|
-
log,
|
|
1036
|
-
readUsage,
|
|
1037
|
-
memory,
|
|
1038
|
-
guard,
|
|
1039
|
-
audit: auditor,
|
|
1040
|
-
notify: notifyParent,
|
|
1041
|
-
// Live delivery into a running child. The steerer reads both services at
|
|
1042
|
-
// call time; the inspector gives the orchestrator the child's inbox state
|
|
1043
|
-
// at the moment its attempt ends, before disposal.
|
|
1044
|
-
steerChild: createChildSteerer({ getSubagents, getAgents, log }),
|
|
1045
|
-
inspectChild(childId) {
|
|
1046
|
-
const agent = getAgents()?.get?.(childId)
|
|
1047
|
-
return { live: Boolean(agent), pending: pendingIds(agent) }
|
|
1048
|
-
},
|
|
1049
|
-
watchChild: createChildWatcher({
|
|
1050
|
-
resolveChild: childId => getAgents()?.get?.(childId),
|
|
1051
|
-
intervalMs: cfg.injectPollMs,
|
|
1052
|
-
}),
|
|
1053
|
-
async spawnChild({ label, prompt, parent, signal, model, runId }) {
|
|
1054
|
-
const subagents = getSubagents()
|
|
1055
|
-
if (!subagents || typeof subagents.startActivation !== 'function') {
|
|
1056
|
-
const error = new Error('subagent service is unavailable; dsh-superagent needs the host subagents service')
|
|
1057
|
-
// The service can also disappear in the middle of a run, when the host
|
|
1058
|
-
// is shutting down. The orchestrator turns this code into `interrupted`
|
|
1059
|
-
// instead of a failed subtask, so the run stays resumable.
|
|
1060
|
-
error.code = 'subagent-unavailable'
|
|
1061
|
-
throw error
|
|
1062
|
-
}
|
|
1063
|
-
const provider = typeof subagents.getProvider === 'function' ? subagents.getProvider(cfg.provider) : undefined
|
|
1064
|
-
const capabilities = provider?.capabilities ?? null
|
|
1065
|
-
const agentOptions = {}
|
|
1066
|
-
// Only the self-heal round passes a model override; everything else keeps
|
|
1067
|
-
// the configured route.
|
|
1068
|
-
const childModel = model ?? cfg.childModel
|
|
1069
|
-
if (cfg.childProvider) agentOptions.provider = cfg.childProvider
|
|
1070
|
-
if (childModel) agentOptions.model = childModel
|
|
1071
|
-
const request = {
|
|
1072
|
-
parent,
|
|
1073
|
-
prompt: [{ type: 'text', text: prompt }],
|
|
1074
|
-
...(Object.keys(agentOptions).length > 0 ? { agentOptions } : {}),
|
|
1075
|
-
}
|
|
1076
|
-
// A preset is the host's only way to give a child a narrower tool set:
|
|
1077
|
-
// the start request has no tool filter in dsh 0.2.2-rc.1.
|
|
1078
|
-
if (cfg.childPreset) {
|
|
1079
|
-
if (capabilities && !capabilities.agentPreset) {
|
|
1080
|
-
throw new Error(
|
|
1081
|
-
`childPreset "${cfg.childPreset}" cannot be applied: subagent provider "${cfg.provider}" does not support `
|
|
1082
|
-
+ 'independent agent presets, so this child would run with this session\'s tools',
|
|
1083
|
-
)
|
|
1084
|
-
}
|
|
1085
|
-
request.agentPreset = cfg.childPreset
|
|
1086
|
-
}
|
|
1087
|
-
// Recursion is bounded unless the operator explicitly left it to the
|
|
1088
|
-
// backend. Silently dropping the cap would hand 8 parallel workers the
|
|
1089
|
-
// right to spawn their own armies.
|
|
1090
|
-
if (cfg.maxSubagentDepth !== 'provider-managed') {
|
|
1091
|
-
if (capabilities && !capabilities.depthLimit) {
|
|
1092
|
-
throw new Error(
|
|
1093
|
-
`subagent provider "${cfg.provider}" cannot enforce maxSubagentDepth (${cfg.maxSubagentDepth}), so child `
|
|
1094
|
-
+ 'agents could spawn their own children without limit; set maxSubagentDepth: provider-managed to accept '
|
|
1095
|
-
+ 'the backend\'s own cap',
|
|
1096
|
-
)
|
|
1097
|
-
}
|
|
1098
|
-
request.maxDepth = cfg.maxSubagentDepth
|
|
1099
|
-
}
|
|
1100
|
-
const activation = await subagents.startActivation({
|
|
1101
|
-
provider: cfg.provider,
|
|
1102
|
-
label,
|
|
1103
|
-
request,
|
|
1104
|
-
signal,
|
|
1105
|
-
delivery: 'caller',
|
|
1106
|
-
})
|
|
1107
|
-
rememberChild(activation.childId)
|
|
1108
|
-
guard.bindChild(activation.childId, { runId, label })
|
|
1109
|
-
return {
|
|
1110
|
-
childId: activation.childId,
|
|
1111
|
-
result: activation.result,
|
|
1112
|
-
dispose: async () => {
|
|
1113
|
-
guard.unbindChild(activation.childId)
|
|
1114
|
-
try {
|
|
1115
|
-
await activation.dispose()
|
|
1116
|
-
} catch (error) {
|
|
1117
|
-
log(`dispose failed for ${activation.childId}: ${error?.message ?? error}`)
|
|
1118
|
-
}
|
|
1119
|
-
},
|
|
1120
|
-
}
|
|
1121
|
-
},
|
|
1122
|
-
})
|
|
1123
|
-
|
|
1124
|
-
// Recovery runs once at mount; tools wait for it so a run left active by a
|
|
1125
|
-
// dead host reads as interrupted before the first tool call sees it. A
|
|
1126
|
-
// failure to initialize the state directory is kept and reported by every
|
|
1127
|
-
// tool: hiding it behind "no runs recorded" is how a broken stateDir looks
|
|
1128
|
-
// like an empty one.
|
|
1129
|
-
let stateError = null
|
|
1130
|
-
const ready = (async () => {
|
|
1131
|
-
try {
|
|
1132
|
-
await orchestrator.recover()
|
|
1133
|
-
} catch (error) {
|
|
1134
|
-
stateError = error instanceof Error ? error : new Error(String(error))
|
|
1135
|
-
log(`state directory is not usable: ${stateError.message}`)
|
|
1136
|
-
return
|
|
1137
|
-
}
|
|
1138
|
-
// Backfill runs that settled while no tool was watching, so the ledger is
|
|
1139
|
-
// complete after a restart. Recording is idempotent: a normal mount adds
|
|
1140
|
-
// nothing for runs already written.
|
|
1141
|
-
try {
|
|
1142
|
-
await recordSpend(await orchestrator.list())
|
|
1143
|
-
} catch (error) {
|
|
1144
|
-
log(`ledger: cannot backfill from runs: ${error?.message ?? error}`)
|
|
1145
|
-
}
|
|
1146
|
-
// Templates are optional: a failure here must not make every run tool
|
|
1147
|
-
// answer with a state error, and the built-ins still work without a file.
|
|
1148
|
-
if (!memoryBlocked) {
|
|
1149
|
-
try {
|
|
1150
|
-
await templates.init()
|
|
1151
|
-
} catch (error) {
|
|
1152
|
-
log(`cannot create the template directory ${templates.dir}: ${error?.message ?? error}`)
|
|
1153
|
-
}
|
|
1154
|
-
}
|
|
1155
|
-
if (!(cfg.keepRuns > 0) || typeof store.prune !== 'function') return
|
|
1156
|
-
try {
|
|
1157
|
-
const { removed } = await store.prune({ olderThanDays: cfg.keepRuns })
|
|
1158
|
-
if (removed.length > 0) {
|
|
1159
|
-
log(`pruned ${removed.length} terminal run(s) older than ${cfg.keepRuns} day(s): ${removed.join(', ')}`)
|
|
1160
|
-
}
|
|
1161
|
-
} catch (error) {
|
|
1162
|
-
log(`cannot prune old runs: ${error?.message ?? error}`)
|
|
1163
|
-
}
|
|
1164
|
-
})()
|
|
1165
|
-
|
|
1166
|
-
/** True when the host actually provides a subagent service. */
|
|
1167
|
-
function hasSubagents() {
|
|
1168
|
-
const subagents = getSubagents()
|
|
1169
|
-
return Boolean(subagents && typeof subagents.startActivation === 'function')
|
|
1170
|
-
}
|
|
1171
|
-
|
|
1172
|
-
function requireAgent(exec) {
|
|
1173
|
-
const agent = exec?.agent
|
|
1174
|
-
if (!agent || typeof agent !== 'object' || !agent.id) return { error: describeError('no live agent in this tool call context') }
|
|
1175
|
-
if (childIds.has(agent.id)) {
|
|
1176
|
-
return { error: describeError('refused: a superagent worker may not start, resume, or cancel runs; finish your subtask instead') }
|
|
1177
|
-
}
|
|
1178
|
-
return { agent }
|
|
1179
|
-
}
|
|
1180
|
-
|
|
1181
|
-
/**
|
|
1182
|
-
* Resolve the session named by an HTTP caller. An embedded start is a normal
|
|
1183
|
-
* run: it needs a live agent to own the children, and the same recursion
|
|
1184
|
-
* guard as a tool call. A synthetic parent would spawn children no session
|
|
1185
|
-
* owns, so a missing session is an error, never a fallback.
|
|
1186
|
-
* @param {unknown} sessionId - `session_id` from the request body.
|
|
1187
|
-
* @returns {object} live agent.
|
|
1188
|
-
*/
|
|
1189
|
-
function resolveSession(sessionId) {
|
|
1190
|
-
const id = typeof sessionId === 'string' ? sessionId.trim() : ''
|
|
1191
|
-
if (!id) {
|
|
1192
|
-
throw new Error(
|
|
1193
|
-
'no live agent: session_id is required; an HTTP-started run needs an open session to own its child agents',
|
|
1194
|
-
)
|
|
1195
|
-
}
|
|
1196
|
-
const agents = typeof ctx.get === 'function' ? ctx.get('agents') : undefined
|
|
1197
|
-
const agent = agents && typeof agents.get === 'function' ? agents.get(id) : undefined
|
|
1198
|
-
if (!agent || typeof agent !== 'object' || !agent.id) {
|
|
1199
|
-
throw new Error(
|
|
1200
|
-
`no live agent: session ${id} is not open in this host process; open that session, or start the run from a `
|
|
1201
|
-
+ 'tool call inside it',
|
|
1202
|
-
)
|
|
1203
|
-
}
|
|
1204
|
-
if (childIds.has(agent.id)) {
|
|
1205
|
-
throw new Error('refused: a superagent worker may not start or resume runs; finish your subtask instead')
|
|
1206
|
-
}
|
|
1207
|
-
return agent
|
|
1208
|
-
}
|
|
1209
|
-
|
|
1210
|
-
ctx.tools.register(defineTool({
|
|
1211
|
-
name: 'superagent_start',
|
|
1212
|
-
description:
|
|
1213
|
-
'Start a long-horizon autonomous run: a planner decomposes the goal into subtasks, '
|
|
1214
|
-
+ 'independent subtasks run in parallel child agents while ones with a declared dependency wait for it, '
|
|
1215
|
-
+ 'and their reports are merged into one final report. '
|
|
1216
|
-
+ 'Pass mode "direct" for a single self-contained task instead: one worker does it, there is no planner '
|
|
1217
|
-
+ 'or aggregator, and its reply is the report verbatim — use it for one lookup, one edit, one query, or '
|
|
1218
|
-
+ 'one short piece of writing, not for a goal with parts that can be worked in parallel. '
|
|
1219
|
-
+ 'The call returns immediately with a run id; poll it with superagent_status. Runs are persisted, '
|
|
1220
|
-
+ 'so they survive a host restart and can be resumed or cancelled.',
|
|
1221
|
-
properties: {
|
|
1222
|
-
goal: { type: 'string', description: 'The complete goal for the run. Be specific about the expected outcome.' },
|
|
1223
|
-
mode: {
|
|
1224
|
-
type: 'string',
|
|
1225
|
-
enum: ['planned', 'direct'],
|
|
1226
|
-
description: 'planned (default): planner, parallel workers, merged report. direct: one worker runs the whole '
|
|
1227
|
-
+ 'goal, with no planning or aggregation, and its reply is returned unchanged. Choose direct only when the '
|
|
1228
|
-
+ 'task is one self-contained pass that gains nothing from splitting.',
|
|
1229
|
-
},
|
|
1230
|
-
queue: {
|
|
1231
|
-
type: 'boolean',
|
|
1232
|
-
description: 'When maxActiveRuns is already in use, wait for a free slot instead of failing. The run returns '
|
|
1233
|
-
+ `status "queued" with its position, starts automatically when another run finishes, and gives up after `
|
|
1234
|
-
+ `queueTimeoutMinutes (default ${DEFAULTS.queueTimeoutMinutes}). Off by default; at most maxQueuedRuns `
|
|
1235
|
-
+ `(default ${DEFAULTS.maxQueuedRuns}) may wait.`,
|
|
1236
|
-
},
|
|
1237
|
-
max_subtasks: { type: 'number', description: `Cap on planned subtasks (default ${DEFAULTS.maxSubtasks}, max 16).` },
|
|
1238
|
-
max_parallel: { type: 'number', description: `Subtasks allowed to run at once (default ${DEFAULTS.maxParallel}, max 8).` },
|
|
1239
|
-
deadline_minutes: { type: 'number', description: `Wall-clock budget in minutes (default ${DEFAULTS.deadlineMinutes}).` },
|
|
1240
|
-
allow_duplicate: {
|
|
1241
|
-
type: 'boolean',
|
|
1242
|
-
description: 'Start a second run for the same goal even when an active run already has it. '
|
|
1243
|
-
+ 'By default the active run id is returned instead, so a retry cannot double the spend.',
|
|
1244
|
-
},
|
|
1245
|
-
approve_policy: {
|
|
1246
|
-
type: 'boolean',
|
|
1247
|
-
description: 'Release a start that the permission policy holds for confirmation. The approval is '
|
|
1248
|
-
+ 'recorded in the audit trail. It cannot override a policy that denies the start.',
|
|
1249
|
-
},
|
|
1250
|
-
wait_seconds: { type: 'number', description: 'Block up to this many seconds for a terminal status before returning (0 returns immediately).' },
|
|
1251
|
-
},
|
|
1252
|
-
required: ['goal'],
|
|
1253
|
-
async execute(args = {}, exec) {
|
|
1254
|
-
const check = requireAgent(exec)
|
|
1255
|
-
if (check.error) return check.error
|
|
1256
|
-
try {
|
|
1257
|
-
await ready
|
|
1258
|
-
if (stateError) return describeError(stateError)
|
|
1259
|
-
if (!hasSubagents()) {
|
|
1260
|
-
return describeError(
|
|
1261
|
-
'subagent service is unavailable; dsh-superagent needs the host subagents service to create planner, '
|
|
1262
|
-
+ 'worker, and aggregator agents. Enable it in this profile (the base bundle provides it) and restart.',
|
|
1263
|
-
)
|
|
1264
|
-
}
|
|
1265
|
-
const run = await orchestrator.start({
|
|
1266
|
-
goal: args.goal,
|
|
1267
|
-
parentSessionId: check.agent.id,
|
|
1268
|
-
parent: check.agent,
|
|
1269
|
-
clientTimeZone: exec.clientTimeZone,
|
|
1270
|
-
allowDuplicate: args.allow_duplicate === true,
|
|
1271
|
-
mode: args.mode,
|
|
1272
|
-
queue: args.queue === true,
|
|
1273
|
-
approvePolicy: args.approve_policy === true,
|
|
1274
|
-
overrides: {
|
|
1275
|
-
maxSubtasks: args.max_subtasks,
|
|
1276
|
-
maxParallel: args.max_parallel,
|
|
1277
|
-
deadlineMinutes: args.deadline_minutes,
|
|
1278
|
-
},
|
|
1279
|
-
})
|
|
1280
|
-
const waitSeconds = Number(args.wait_seconds) || 0
|
|
1281
|
-
if (waitSeconds > 0) {
|
|
1282
|
-
const finished = await orchestrator.status(run.id, waitSeconds)
|
|
1283
|
-
await recordSpend([finished])
|
|
1284
|
-
// `status` reads the stored run, which never has the transient join
|
|
1285
|
-
// marker; carry it over so the caller can still see it joined.
|
|
1286
|
-
return formatRun(run.deduped ? { ...finished, deduped: true } : finished)
|
|
1287
|
-
}
|
|
1288
|
-
if (run.queue?.waiting) {
|
|
1289
|
-
return `${formatRun(run, { includeReport: false })}\n\nQueued, not started: the run begins automatically when `
|
|
1290
|
-
+ 'an active run finishes. Poll with superagent_status or cancel it with superagent_cancel.'
|
|
1291
|
-
}
|
|
1292
|
-
return `${formatRun(run, { includeReport: false })}\n\nStarted in the background. Poll with superagent_status; `
|
|
1293
|
-
+ 'the run keeps going after this tool call returns.'
|
|
1294
|
-
} catch (error) {
|
|
1295
|
-
return describeError(error)
|
|
1296
|
-
}
|
|
1297
|
-
},
|
|
1298
|
-
}))
|
|
1299
|
-
|
|
1300
|
-
ctx.tools.register(defineTool({
|
|
1301
|
-
name: 'superagent_status',
|
|
1302
|
-
description:
|
|
1303
|
-
'Read one superagent run: status, subtask outcomes, measured token usage, and the final report. '
|
|
1304
|
-
+ 'With wait_seconds it blocks until the run reaches a terminal state or the wait expires.',
|
|
1305
|
-
properties: {
|
|
1306
|
-
run_id: { type: 'string', description: 'Run id returned by superagent_start.' },
|
|
1307
|
-
wait_seconds: { type: 'number', description: 'Block up to this many seconds for a terminal state (default 0).' },
|
|
1308
|
-
},
|
|
1309
|
-
required: ['run_id'],
|
|
1310
|
-
async execute(args = {}) {
|
|
1311
|
-
try {
|
|
1312
|
-
await ready
|
|
1313
|
-
if (stateError) return describeError(stateError)
|
|
1314
|
-
const run = await orchestrator.status(String(args.run_id ?? '').trim(), Number(args.wait_seconds) || 0)
|
|
1315
|
-
await recordSpend([run])
|
|
1316
|
-
return formatRun(run)
|
|
1317
|
-
} catch (error) {
|
|
1318
|
-
return describeError(error)
|
|
1319
|
-
}
|
|
1320
|
-
},
|
|
1321
|
-
}))
|
|
1322
|
-
|
|
1323
|
-
ctx.tools.register(defineTool({
|
|
1324
|
-
name: 'superagent_list',
|
|
1325
|
-
description: 'List recorded superagent runs, newest first, with status and progress.',
|
|
1326
|
-
properties: {
|
|
1327
|
-
limit: { type: 'number', description: 'Maximum rows to print (default 20).' },
|
|
1328
|
-
},
|
|
1329
|
-
async execute(args = {}) {
|
|
1330
|
-
try {
|
|
1331
|
-
await ready
|
|
1332
|
-
if (stateError) return describeError(stateError)
|
|
1333
|
-
const runs = await orchestrator.list()
|
|
1334
|
-
await recordSpend(runs)
|
|
1335
|
-
const stats = typeof store.stats === 'function' ? await store.stats() : null
|
|
1336
|
-
const memoryStats = memory
|
|
1337
|
-
? await memory.stats({ scope: cfg.memoryScope, maxAgeDays: cfg.memoryMaxAgeDays }).catch(() => null)
|
|
1338
|
-
: null
|
|
1339
|
-
const notifyState = await notifyPolicy.summary().catch(() => null)
|
|
1340
|
-
const ledgerStats = await ledger
|
|
1341
|
-
.summarize({ since: Date.now() - LEDGER_WINDOW_DAYS * 86400000 })
|
|
1342
|
-
.catch(() => null)
|
|
1343
|
-
const extra = stats
|
|
1344
|
-
? {
|
|
1345
|
-
...stats,
|
|
1346
|
-
root: store.root,
|
|
1347
|
-
memory: memoryStats,
|
|
1348
|
-
pendingNotifications: notifyState?.pending?.length ?? 0,
|
|
1349
|
-
ledger: ledgerStats,
|
|
1350
|
-
ledgerDays: LEDGER_WINDOW_DAYS,
|
|
1351
|
-
}
|
|
1352
|
-
: null
|
|
1353
|
-
return formatList(runs, Math.max(1, Math.min(100, Number(args.limit) || 20)), extra)
|
|
1354
|
-
} catch (error) {
|
|
1355
|
-
return describeError(error)
|
|
1356
|
-
}
|
|
1357
|
-
},
|
|
1358
|
-
}))
|
|
1359
|
-
|
|
1360
|
-
ctx.tools.register(defineTool({
|
|
1361
|
-
name: 'superagent_cancel',
|
|
1362
|
-
description:
|
|
1363
|
-
'Cancel a superagent run: stops running subtasks, marks the run cancelled, and keeps the state file '
|
|
1364
|
-
+ 'so the partial work stays inspectable.',
|
|
1365
|
-
properties: {
|
|
1366
|
-
run_id: { type: 'string', description: 'Run id to cancel.' },
|
|
1367
|
-
},
|
|
1368
|
-
required: ['run_id'],
|
|
1369
|
-
async execute(args = {}, exec) {
|
|
1370
|
-
const check = requireAgent(exec)
|
|
1371
|
-
if (check.error) return check.error
|
|
1372
|
-
try {
|
|
1373
|
-
await ready
|
|
1374
|
-
if (stateError) return describeError(stateError)
|
|
1375
|
-
const run = await orchestrator.cancel(String(args.run_id ?? '').trim())
|
|
1376
|
-
await recordSpend([run])
|
|
1377
|
-
const head = run.status === 'cancelled'
|
|
1378
|
-
? `cancelled ${run.id}`
|
|
1379
|
-
: run.cancelPending
|
|
1380
|
-
? `cancel requested for ${run.id}, not confirmed by the owning process yet`
|
|
1381
|
-
: `${run.id} is ${run.status}; nothing to cancel`
|
|
1382
|
-
return `${head}\n\n${formatRun(run, { includeReport: false })}`
|
|
1383
|
-
} catch (error) {
|
|
1384
|
-
return describeError(error)
|
|
1385
|
-
}
|
|
1386
|
-
},
|
|
1387
|
-
}))
|
|
1388
|
-
|
|
1389
|
-
ctx.tools.register(defineTool({
|
|
1390
|
-
name: 'superagent_resume',
|
|
1391
|
-
description:
|
|
1392
|
-
'Resume a run that was interrupted by a host restart, ran out of time, or failed part way. '
|
|
1393
|
-
+ 'Completed subtasks are kept; pending and failed ones run again. A completed run is reopened only when it '
|
|
1394
|
-
+ 'holds an answer that never reached a prompt, so its aggregation can apply the decision.',
|
|
1395
|
-
properties: {
|
|
1396
|
-
run_id: { type: 'string', description: 'Run id to resume.' },
|
|
1397
|
-
wait_seconds: { type: 'number', description: 'Block up to this many seconds for a terminal state (default 0).' },
|
|
1398
|
-
force: {
|
|
1399
|
-
type: 'boolean',
|
|
1400
|
-
description: 'Accepted for backward compatibility and ignored: a resume is never refused by maxActiveRuns.',
|
|
1401
|
-
},
|
|
1402
|
-
approve_policy: {
|
|
1403
|
-
type: 'boolean',
|
|
1404
|
-
description: 'Release a resume that the permission policy holds for confirmation. The approval is '
|
|
1405
|
-
+ 'recorded in the audit trail. It cannot override a policy that denies the resume.',
|
|
1406
|
-
},
|
|
1407
|
-
},
|
|
1408
|
-
required: ['run_id'],
|
|
1409
|
-
async execute(args = {}, exec) {
|
|
1410
|
-
const check = requireAgent(exec)
|
|
1411
|
-
if (check.error) return check.error
|
|
1412
|
-
try {
|
|
1413
|
-
await ready
|
|
1414
|
-
if (stateError) return describeError(stateError)
|
|
1415
|
-
if (!hasSubagents()) {
|
|
1416
|
-
return describeError(
|
|
1417
|
-
'subagent service is unavailable; resuming a run needs the host subagents service to create child agents.',
|
|
1418
|
-
)
|
|
1419
|
-
}
|
|
1420
|
-
const run = await orchestrator.resume(
|
|
1421
|
-
String(args.run_id ?? '').trim(),
|
|
1422
|
-
check.agent,
|
|
1423
|
-
exec.clientTimeZone,
|
|
1424
|
-
{ force: args.force === true, approvePolicy: args.approve_policy === true },
|
|
1425
|
-
)
|
|
1426
|
-
const waitSeconds = Number(args.wait_seconds) || 0
|
|
1427
|
-
const current = waitSeconds > 0 ? await orchestrator.status(run.id, waitSeconds) : run
|
|
1428
|
-
await recordSpend([current])
|
|
1429
|
-
return formatRun(current)
|
|
1430
|
-
} catch (error) {
|
|
1431
|
-
return describeError(error)
|
|
1432
|
-
}
|
|
1433
|
-
},
|
|
1434
|
-
}))
|
|
1435
|
-
|
|
1436
|
-
ctx.tools.register(defineTool({
|
|
1437
|
-
name: 'superagent_followup',
|
|
1438
|
-
description:
|
|
1439
|
-
'Add an instruction to a run that is already executing, instead of starting a second run. This is not a live '
|
|
1440
|
-
+ 'channel to the running children: the host has no way to append a message to a child activation, so the '
|
|
1441
|
-
+ 'instruction is queued on the run and carried by the next prompt built for it — the next worker spawn or the '
|
|
1442
|
-
+ 'aggregation, whichever comes first. Subtasks that are already running or finished keep their results. The '
|
|
1443
|
-
+ 'reply states exactly which boundary it will reach.',
|
|
1444
|
-
properties: {
|
|
1445
|
-
run_id: { type: 'string', description: 'Run id returned by superagent_start.' },
|
|
1446
|
-
message: { type: 'string', description: 'The instruction or constraint to add.' },
|
|
1447
|
-
},
|
|
1448
|
-
required: ['run_id', 'message'],
|
|
1449
|
-
async execute(args = {}, exec) {
|
|
1450
|
-
const check = requireAgent(exec)
|
|
1451
|
-
if (check.error) return check.error
|
|
1452
|
-
try {
|
|
1453
|
-
await ready
|
|
1454
|
-
if (stateError) return describeError(stateError)
|
|
1455
|
-
const result = await orchestrator.followup(
|
|
1456
|
-
String(args.run_id ?? '').trim(),
|
|
1457
|
-
args.message,
|
|
1458
|
-
check.agent,
|
|
1459
|
-
)
|
|
1460
|
-
return [
|
|
1461
|
-
`instruction ${result.followup.id} added to run ${result.run.id} — ${result.run.status}`,
|
|
1462
|
-
`when it takes effect: ${result.effect.detail} (boundary: ${result.effect.boundary}).`,
|
|
1463
|
-
'A child that is already running is not interrupted and does not see it.',
|
|
1464
|
-
'',
|
|
1465
|
-
formatRun(result.run, { includeReport: false }),
|
|
1466
|
-
].join('\n')
|
|
1467
|
-
} catch (error) {
|
|
1468
|
-
return describeError(error)
|
|
1469
|
-
}
|
|
1470
|
-
},
|
|
1471
|
-
}))
|
|
1472
|
-
|
|
1473
|
-
ctx.tools.register(defineTool({
|
|
1474
|
-
name: 'superagent_inject',
|
|
1475
|
-
description:
|
|
1476
|
-
'Deliver an instruction into the workers that are running right now, instead of waiting for the next prompt. '
|
|
1477
|
-
+ 'The host reads steering at a child\'s next step boundary, so the message becomes part of that child\'s next '
|
|
1478
|
-
+ 'model request: it never interrupts a model call already in flight, and it arrives only after the current step '
|
|
1479
|
-
+ '(the model response plus its tool batch) finishes. A live child that had already decided to stop runs one more '
|
|
1480
|
-
+ 'turn to read it. The reply reports the measured delay from acceptance to the child\'s next request; a message '
|
|
1481
|
-
+ 'the child never claimed is reported as missed, never as delivered. Use superagent_followup when no worker is '
|
|
1482
|
-
+ 'running or the instruction can wait for the next prompt.',
|
|
1483
|
-
properties: {
|
|
1484
|
-
run_id: { type: 'string', description: 'Run id returned by superagent_start.' },
|
|
1485
|
-
message: { type: 'string', description: 'The instruction or constraint the running workers should read next.' },
|
|
1486
|
-
subtask_index: {
|
|
1487
|
-
type: 'number',
|
|
1488
|
-
description: 'Narrow delivery to one running worker, using its index from superagent_status. Omit to reach every running worker.',
|
|
1489
|
-
},
|
|
1490
|
-
wait_seconds: {
|
|
1491
|
-
type: 'number',
|
|
1492
|
-
description: 'Block up to this many seconds for the children to claim the message, so the reply can report the measured delay (default 0).',
|
|
1493
|
-
},
|
|
1494
|
-
},
|
|
1495
|
-
required: ['run_id', 'message'],
|
|
1496
|
-
async execute(args = {}, exec) {
|
|
1497
|
-
const check = requireAgent(exec)
|
|
1498
|
-
if (check.error) return check.error
|
|
1499
|
-
try {
|
|
1500
|
-
await ready
|
|
1501
|
-
if (stateError) return describeError(stateError)
|
|
1502
|
-
const result = await orchestrator.inject(
|
|
1503
|
-
String(args.run_id ?? '').trim(),
|
|
1504
|
-
args.message,
|
|
1505
|
-
check.agent,
|
|
1506
|
-
{ subtaskIndex: args.subtask_index },
|
|
1507
|
-
)
|
|
1508
|
-
const entry = await orchestrator.waitForInjection(result.run, result.injection, args.wait_seconds)
|
|
1509
|
-
return formatInjectionReply(result.run, entry, result.degraded, { pollMs: cfg.injectPollMs })
|
|
1510
|
-
} catch (error) {
|
|
1511
|
-
return describeError(error)
|
|
1512
|
-
}
|
|
1513
|
-
},
|
|
1514
|
-
}))
|
|
1515
|
-
|
|
1516
|
-
ctx.tools.register(defineTool({
|
|
1517
|
-
name: 'superagent_answer',
|
|
1518
|
-
description:
|
|
1519
|
-
'Answer a question a run asked — the "needs your decision" item with a qN id — so that run continues with the '
|
|
1520
|
-
+ 'decision instead of a new run being started. An active run applies it at its next boundary; a finished run '
|
|
1521
|
-
+ 'is reopened and only its aggregation runs again, now with the answer. The answer is matched to one specific '
|
|
1522
|
-
+ 'question: an unknown, already answered, or expired question is refused instead of being attached to whatever '
|
|
1523
|
-
+ 'is open.',
|
|
1524
|
-
properties: {
|
|
1525
|
-
run_id: { type: 'string', description: 'Run id returned by superagent_start.' },
|
|
1526
|
-
attention_id: {
|
|
1527
|
-
type: 'string',
|
|
1528
|
-
description: 'Question id from superagent_status, e.g. q1. Required when the run has more than one open question.',
|
|
1529
|
-
},
|
|
1530
|
-
answer: { type: 'string', description: 'The decision itself; one of the listed options is enough, free text is allowed.' },
|
|
1531
|
-
wait_seconds: { type: 'number', description: 'Block up to this many seconds for the run to settle again (default 0).' },
|
|
1532
|
-
},
|
|
1533
|
-
required: ['run_id', 'answer'],
|
|
1534
|
-
async execute(args = {}, exec) {
|
|
1535
|
-
const check = requireAgent(exec)
|
|
1536
|
-
if (check.error) return check.error
|
|
1537
|
-
try {
|
|
1538
|
-
await ready
|
|
1539
|
-
if (stateError) return describeError(stateError)
|
|
1540
|
-
const result = await orchestrator.answer(
|
|
1541
|
-
String(args.run_id ?? '').trim(),
|
|
1542
|
-
args.attention_id,
|
|
1543
|
-
args.answer,
|
|
1544
|
-
check.agent,
|
|
1545
|
-
exec.clientTimeZone,
|
|
1546
|
-
)
|
|
1547
|
-
let head
|
|
1548
|
-
if (result.resumed) {
|
|
1549
|
-
head = `answered ${result.attentionId} on run ${result.run.id}; the run was reopened and is ${result.run.status} `
|
|
1550
|
-
+ `again — it applies the answer at ${result.effect.detail}`
|
|
1551
|
-
} else if (result.reason) {
|
|
1552
|
-
head = `answered ${result.attentionId} on run ${result.run.id}, but the run was not restarted: ${result.reason}. `
|
|
1553
|
-
+ 'The answer is saved; call superagent_resume when you want it applied.'
|
|
1554
|
-
} else {
|
|
1555
|
-
head = `answered ${result.attentionId} on run ${result.run.id}; it takes effect at ${result.effect.detail}`
|
|
1556
|
-
}
|
|
1557
|
-
const waitSeconds = Number(args.wait_seconds) || 0
|
|
1558
|
-
const current = result.resumed && waitSeconds > 0
|
|
1559
|
-
? await orchestrator.status(result.run.id, waitSeconds)
|
|
1560
|
-
: result.run
|
|
1561
|
-
return `${head}.\n\n${formatRun(current)}`
|
|
1562
|
-
} catch (error) {
|
|
1563
|
-
return describeError(error)
|
|
1564
|
-
}
|
|
1565
|
-
},
|
|
1566
|
-
}))
|
|
1567
|
-
|
|
1568
|
-
ctx.tools.register(defineTool({
|
|
1569
|
-
name: 'superagent_memory',
|
|
1570
|
-
description:
|
|
1571
|
-
'Read or correct the cross-run notebook: short notes that earlier runs left for the next one. '
|
|
1572
|
-
+ 'A note is advisory and can be stale; a new note with the same key supersedes it, and forget retracts it.',
|
|
1573
|
-
properties: {
|
|
1574
|
-
action: {
|
|
1575
|
-
type: 'string',
|
|
1576
|
-
enum: ['list', 'search', 'set', 'forget'],
|
|
1577
|
-
description: 'List notes, search them by keyword or tag, set (add or correct) one, or forget one.',
|
|
1578
|
-
},
|
|
1579
|
-
key: { type: 'string', description: 'Short topic key. A new note with the same key replaces the older one.' },
|
|
1580
|
-
kind: { type: 'string', enum: [...MEMORY_KINDS], description: 'decision, pitfall, next, dispatch, or note.' },
|
|
1581
|
-
text: { type: 'string', description: 'The durable fact to record (set only).' },
|
|
1582
|
-
query: {
|
|
1583
|
-
type: 'string',
|
|
1584
|
-
description: 'Keywords to rank notes by (search only). The goal of the current task works well.',
|
|
1585
|
-
},
|
|
1586
|
-
tags: {
|
|
1587
|
-
type: 'array',
|
|
1588
|
-
items: { type: 'string' },
|
|
1589
|
-
description: 'Topic labels to match exactly (search) or to attach to a note (set).',
|
|
1590
|
-
},
|
|
1591
|
-
scope: {
|
|
1592
|
-
type: 'string',
|
|
1593
|
-
description: 'Notebook scope: "rules" for project rules, "profile" for user preferences, '
|
|
1594
|
-
+ 'or the run scope (default) that earlier runs write to.',
|
|
1595
|
-
},
|
|
1596
|
-
limit: { type: 'number', description: 'Maximum notes to print (default 20).' },
|
|
1597
|
-
},
|
|
1598
|
-
required: ['action'],
|
|
1599
|
-
async execute(args = {}, exec) {
|
|
1600
|
-
const check = requireAgent(exec)
|
|
1601
|
-
if (check.error) return check.error
|
|
1602
|
-
if (!memory) {
|
|
1603
|
-
return describeError(
|
|
1604
|
-
'cross-run memory is disabled (memory: false, or stateDir points inside the installed package)',
|
|
1605
|
-
)
|
|
1606
|
-
}
|
|
1607
|
-
try {
|
|
1608
|
-
await ready
|
|
1609
|
-
if (stateError) return describeError(stateError)
|
|
1610
|
-
const action = String(args.action ?? '').trim().toLowerCase()
|
|
1611
|
-
// A run writes to the configured scope; `rules` and `profile` are
|
|
1612
|
-
// curated by hand and read into every run, so the tool can address
|
|
1613
|
-
// them explicitly.
|
|
1614
|
-
const scope = args.scope === undefined || args.scope === null
|
|
1615
|
-
? cfg.memoryScope
|
|
1616
|
-
: normalizeScope(args.scope)
|
|
1617
|
-
if (action === 'list') {
|
|
1618
|
-
// Capped at 30: this output goes straight into the model context, and a
|
|
1619
|
-
// 200-row dump would cost more than the notes are worth.
|
|
1620
|
-
const limit = Math.max(1, Math.min(30, Number(args.limit) || 20))
|
|
1621
|
-
const result = await memory.list({ scope, limit, maxAgeDays: cfg.memoryMaxAgeDays })
|
|
1622
|
-
if (result.total === 0) return `no notes recorded in scope "${scope}" (${result.path})`
|
|
1623
|
-
const rows = result.entries.map(entry => `- ${entry.key} [${entry.kind}] ${entry.text}`)
|
|
1624
|
-
const notes = result.bad ? `\n\n${result.bad} unreadable line(s) skipped` : ''
|
|
1625
|
-
return `${result.total} note(s) in scope "${scope}" (${result.path})\n\n${rows.join('\n')}${notes}`
|
|
1626
|
-
}
|
|
1627
|
-
if (action === 'search') {
|
|
1628
|
-
const query = String(args.query ?? '').trim()
|
|
1629
|
-
const tags = Array.isArray(args.tags) ? args.tags : []
|
|
1630
|
-
if (!query && tags.length === 0) {
|
|
1631
|
-
return describeError('search needs a query, tags, or both; call action="list" to read everything')
|
|
1632
|
-
}
|
|
1633
|
-
const limit = Math.max(1, Math.min(20, Number(args.limit) || 10))
|
|
1634
|
-
const result = await memory.recall({
|
|
1635
|
-
scope,
|
|
1636
|
-
query,
|
|
1637
|
-
tags,
|
|
1638
|
-
maxEntries: limit,
|
|
1639
|
-
maxAgeDays: cfg.memoryMaxAgeDays,
|
|
1640
|
-
})
|
|
1641
|
-
if (result.matched === 0) {
|
|
1642
|
-
return `no note in scope "${scope}" matches ${query ? `“${query}”` : 'those tags'} `
|
|
1643
|
-
+ `(${result.total} note(s) recorded; action="list" shows them all)`
|
|
1644
|
-
}
|
|
1645
|
-
// The score and its parts are printed so a ranking can be argued with
|
|
1646
|
-
// instead of taken on faith.
|
|
1647
|
-
const rows = result.entries.map(entry => {
|
|
1648
|
-
const run = entry.source.runId ?? 'manual'
|
|
1649
|
-
return `- ${entry.key} [${entry.kind}] score ${entry.score.toFixed(2)} `
|
|
1650
|
-
+ `(keyword ${entry.keyword.toFixed(2)}, tag ${entry.tag.toFixed(2)}) `
|
|
1651
|
-
+ `from run ${run}, ${String(entry.source.ts ?? '').slice(0, 10)}: ${entry.text}`
|
|
1652
|
-
})
|
|
1653
|
-
return `${result.matched} of ${result.total} note(s) in scope "${scope}" match, best first\n\n${rows.join('\n')}`
|
|
1654
|
-
}
|
|
1655
|
-
if (action === 'forget') {
|
|
1656
|
-
const key = String(args.key ?? '').trim()
|
|
1657
|
-
if (!key) return describeError('forget needs the key of the note to retract; call action="list" first')
|
|
1658
|
-
const result = await memory.forget({ scope, key })
|
|
1659
|
-
return result.forgotten
|
|
1660
|
-
? `retracted "${key}" in scope "${scope}"; later runs will not see it`
|
|
1661
|
-
: describeError(result.reason ?? 'cannot retract that note')
|
|
1662
|
-
}
|
|
1663
|
-
if (action === 'set') {
|
|
1664
|
-
const key = String(args.key ?? '').trim()
|
|
1665
|
-
const text = String(args.text ?? '').trim()
|
|
1666
|
-
if (!key || !text) return describeError('set needs both key and text')
|
|
1667
|
-
const result = await memory.set({ scope, key, kind: args.kind, text, tags: args.tags })
|
|
1668
|
-
return result.written > 0
|
|
1669
|
-
? `recorded "${key}" in scope "${scope}"; later runs will see it`
|
|
1670
|
-
: describeError(result.reason ?? 'cannot record that note')
|
|
1671
|
-
}
|
|
1672
|
-
return describeError(`unknown action "${args.action}"; use list, search, set, or forget`)
|
|
1673
|
-
} catch (error) {
|
|
1674
|
-
return describeError(error)
|
|
1675
|
-
}
|
|
1676
|
-
},
|
|
1677
|
-
}))
|
|
1678
|
-
|
|
1679
|
-
/**
|
|
1680
|
-
* A template failure already names the concrete problem (which parameters
|
|
1681
|
-
* are missing, which field is not allowed), so it gets its own hint instead
|
|
1682
|
-
* of the generic "this came from the host" text.
|
|
1683
|
-
*/
|
|
1684
|
-
function templateProblem(error) {
|
|
1685
|
-
const hints = {
|
|
1686
|
-
'missing-parameters': 'pass every declared parameter in params={...}; a template never guesses a default, '
|
|
1687
|
-
+ 'and action="show" lists each parameter with what it should contain',
|
|
1688
|
-
'unknown-parameters': 'remove the parameters the template does not declare, or declare them in a custom '
|
|
1689
|
-
+ 'template saved with action="save"',
|
|
1690
|
-
'builtin-template': 'built-in templates are read-only; save your version under a new id',
|
|
1691
|
-
'unknown-template': 'call action="list" to see the available template ids',
|
|
1692
|
-
}
|
|
1693
|
-
const hint = hints[error.code]
|
|
1694
|
-
?? 'call action="show" on a built-in template to see the accepted fields, then save the corrected definition'
|
|
1695
|
-
return [`[error] ${error.message}`, `hint: ${hint}`].join('\n')
|
|
1696
|
-
}
|
|
1697
|
-
|
|
1698
|
-
ctx.tools.register(defineTool({
|
|
1699
|
-
name: 'superagent_template',
|
|
1700
|
-
description:
|
|
1701
|
-
'List, show, expand, save, or delete a workflow template: a fixed goal skeleton with required parameters, '
|
|
1702
|
-
+ 'the situations it fits, and when it is the wrong tool. Expanding returns one normal goal string, which '
|
|
1703
|
-
+ 'superagent_start plans exactly like a goal typed by the user. A template cannot set limits, budgets, a '
|
|
1704
|
-
+ 'mode, or an override, so using one never widens what a run may do.',
|
|
1705
|
-
properties: {
|
|
1706
|
-
action: {
|
|
1707
|
-
type: 'string',
|
|
1708
|
-
enum: ['list', 'show', 'expand', 'save', 'delete'],
|
|
1709
|
-
description: 'List templates, show one in full, expand one into a goal, save a custom one, or delete a custom one.',
|
|
1710
|
-
},
|
|
1711
|
-
id: { type: 'string', description: 'Template id from action="list". Built-in ids are read-only.' },
|
|
1712
|
-
params: {
|
|
1713
|
-
type: 'object',
|
|
1714
|
-
description: 'Values for the placeholders (expand only). Every declared parameter is required; a missing or '
|
|
1715
|
-
+ 'empty value is refused with its name instead of being given a default.',
|
|
1716
|
-
additionalProperties: { type: 'string' },
|
|
1717
|
-
},
|
|
1718
|
-
template: {
|
|
1719
|
-
type: 'object',
|
|
1720
|
-
description: 'Complete definition (save only): id, title, whenToUse, whenNotToUse (list of strings), '
|
|
1721
|
-
+ 'variables (list of {name, description}), and skeleton with {{name}} placeholders. Unknown fields are '
|
|
1722
|
-
+ 'refused so a template cannot carry limits or overrides.',
|
|
1723
|
-
},
|
|
1724
|
-
limit: { type: 'number', description: 'Maximum templates to list (default 50).' },
|
|
1725
|
-
},
|
|
1726
|
-
required: ['action'],
|
|
1727
|
-
async execute(args = {}, exec) {
|
|
1728
|
-
const check = requireAgent(exec)
|
|
1729
|
-
if (check.error) return check.error
|
|
1730
|
-
try {
|
|
1731
|
-
await ready
|
|
1732
|
-
if (stateError) return describeError(stateError)
|
|
1733
|
-
const action = String(args.action ?? '').trim().toLowerCase()
|
|
1734
|
-
if (action === 'list') {
|
|
1735
|
-
const result = await templates.list()
|
|
1736
|
-
return formatTemplateList(result, Math.max(1, Math.min(100, Number(args.limit) || 50)))
|
|
1737
|
-
}
|
|
1738
|
-
if ((action === 'save' || action === 'delete') && memoryBlocked) {
|
|
1739
|
-
return describeError(
|
|
1740
|
-
`cannot ${action} a template: stateDir ${store.root} is inside the installed package, so writing there `
|
|
1741
|
-
+ 'would modify the shipped files; point stateDir elsewhere',
|
|
1742
|
-
)
|
|
1743
|
-
}
|
|
1744
|
-
if (action === 'show' || action === 'expand') {
|
|
1745
|
-
const id = String(args.id ?? '').trim()
|
|
1746
|
-
if (!id) return describeError(`${action} needs the id of a template; call action="list" first`)
|
|
1747
|
-
const template = await templates.get(id)
|
|
1748
|
-
if (!template) {
|
|
1749
|
-
return describeError(`no workflow template with id "${id}"; call action="list" to see the ids`)
|
|
1750
|
-
}
|
|
1751
|
-
if (action === 'show') return formatTemplateDetail(template)
|
|
1752
|
-
const expanded = expandTemplate(template, args.params)
|
|
1753
|
-
return [
|
|
1754
|
-
`expanded template "${expanded.templateId}" into one goal of ${expanded.goal.length} characters. `
|
|
1755
|
-
+ 'Start it with superagent_start goal=<the text below>; the planner sees the same goal it would '
|
|
1756
|
-
+ 'have seen if you had typed it.',
|
|
1757
|
-
'',
|
|
1758
|
-
expanded.goal,
|
|
1759
|
-
].join('\n')
|
|
1760
|
-
}
|
|
1761
|
-
if (action === 'save') {
|
|
1762
|
-
if (!args.template || typeof args.template !== 'object') {
|
|
1763
|
-
return describeError(
|
|
1764
|
-
'save needs template: the full definition (id, title, whenToUse, whenNotToUse, variables, skeleton)',
|
|
1765
|
-
)
|
|
1766
|
-
}
|
|
1767
|
-
const saved = await templates.save(args.template)
|
|
1768
|
-
return `saved template "${saved.id}"${saved.replaced ? ' (replaced the earlier version)' : ''} at ${saved.path}`
|
|
1769
|
-
}
|
|
1770
|
-
if (action === 'delete') {
|
|
1771
|
-
const id = String(args.id ?? '').trim()
|
|
1772
|
-
if (!id) return describeError('delete needs the id of a custom template; call action="list" first')
|
|
1773
|
-
const result = await templates.remove(id)
|
|
1774
|
-
return result.removed
|
|
1775
|
-
? `deleted custom template "${result.id}"; built-in templates are unaffected`
|
|
1776
|
-
: describeError(`no custom template with id "${result.id}" to delete; built-in templates cannot be deleted`)
|
|
1777
|
-
}
|
|
1778
|
-
return describeError(`unknown action "${args.action}"; use list, show, expand, save, or delete`)
|
|
1779
|
-
} catch (error) {
|
|
1780
|
-
if (error instanceof TemplateError) return templateProblem(error)
|
|
1781
|
-
return describeError(error)
|
|
1782
|
-
}
|
|
1783
|
-
},
|
|
1784
|
-
}))
|
|
1785
|
-
|
|
1786
|
-
// The embedding surface is opt-in: mounting the plugin must not open a port
|
|
1787
|
-
// unasked. When it is on, every request goes through the same orchestrator as
|
|
1788
|
-
// the tools, so quota, budgets, ownership, and cancel behave identically.
|
|
1789
|
-
if (auditor) {
|
|
1790
|
-
ctx.tools.register(defineTool({
|
|
1791
|
-
name: 'superagent_audit',
|
|
1792
|
-
description:
|
|
1793
|
-
'Query the append-only audit trail (tool calls, path writes, commands, blocks, approvals, attention '
|
|
1794
|
-
+ 'decisions, run lifecycle) for one run or a time window, or export the matching events as a single '
|
|
1795
|
-
+ 'JSONL or CSV file.',
|
|
1796
|
-
properties: {
|
|
1797
|
-
run_id: { type: 'string', description: 'Only events for this run id.' },
|
|
1798
|
-
subtask_id: { type: 'string', description: 'Only events for one subtask, e.g. "subtask-2" or "aggregator".' },
|
|
1799
|
-
kind: { type: 'string', description: 'Event kind, e.g. tool.call, path.write, command.exec, blocked, approved, attention.' },
|
|
1800
|
-
decision: { type: 'string', description: 'Only events with this decision: allow, confirm, or deny.' },
|
|
1801
|
-
result: { type: 'string', description: 'Only events with this result, e.g. ok, blocked, pending, approved, failed.' },
|
|
1802
|
-
target: { type: 'string', description: 'Substring of the path, command, or question the event is about.' },
|
|
1803
|
-
since: { type: 'string', description: 'ISO timestamp; events before it are skipped.' },
|
|
1804
|
-
until: { type: 'string', description: 'ISO timestamp; events after it are skipped.' },
|
|
1805
|
-
limit: { type: 'number', description: 'Maximum events to read or rows to print (default 8 for the summary, all for an export).' },
|
|
1806
|
-
order: { type: 'string', description: 'asc (oldest first, default) or desc.' },
|
|
1807
|
-
format: { type: 'string', description: 'summary (default), jsonl, or csv. jsonl and csv write a file and return its path.' },
|
|
1808
|
-
out_path: { type: 'string', description: 'File to write for jsonl/csv. Defaults to <stateDir>/audit/audit-export-<time>.<ext>.' },
|
|
1809
|
-
},
|
|
1810
|
-
async execute(args = {}) {
|
|
1811
|
-
try {
|
|
1812
|
-
await ready
|
|
1813
|
-
if (stateError) return describeError(stateError)
|
|
1814
|
-
const filter = {
|
|
1815
|
-
runId: args.run_id,
|
|
1816
|
-
subtaskId: args.subtask_id,
|
|
1817
|
-
kind: args.kind,
|
|
1818
|
-
decision: args.decision,
|
|
1819
|
-
result: args.result,
|
|
1820
|
-
target: args.target,
|
|
1821
|
-
since: args.since,
|
|
1822
|
-
until: args.until,
|
|
1823
|
-
limit: args.limit,
|
|
1824
|
-
order: String(args.order ?? '').toLowerCase() === 'desc' ? 'desc' : 'asc',
|
|
1825
|
-
}
|
|
1826
|
-
const format = String(args.format ?? 'summary').toLowerCase()
|
|
1827
|
-
if (format === 'jsonl' || format === 'csv') {
|
|
1828
|
-
const written = await auditor.export({ ...filter, format, outFile: args.out_path })
|
|
1829
|
-
return `exported ${written.count} event(s) to ${written.path} (${written.format}, ${formatBytes(written.bytes)})`
|
|
1830
|
-
+ (written.invalid ? `; ${written.invalid} unreadable line(s) were skipped` : '')
|
|
1831
|
-
}
|
|
1832
|
-
if (format !== 'summary') return `unknown format ${JSON.stringify(args.format)}; use summary, jsonl, or csv`
|
|
1833
|
-
const result = await auditor.query(filter)
|
|
1834
|
-
const policyError = await auditor.policyError().catch(() => null)
|
|
1835
|
-
const head = policyError
|
|
1836
|
-
? `policy: ${auditor.policyFile} is invalid, so actions are denied — `
|
|
1837
|
-
+ `${String(policyError.message ?? policyError).split('\n')[0]}\n`
|
|
1838
|
-
: ''
|
|
1839
|
-
return `${head}${formatAudit(result, { limit: Math.min(50, Math.max(1, Number(args.limit) || 8)) })}`
|
|
1840
|
-
} catch (error) {
|
|
1841
|
-
return describeError(error)
|
|
1842
|
-
}
|
|
1843
|
-
},
|
|
1844
|
-
}))
|
|
1845
|
-
}
|
|
1846
|
-
|
|
1847
|
-
if (cfg.controlPort !== null) {
|
|
1848
|
-
const clampControlWait = value => {
|
|
1849
|
-
const seconds = Number(value)
|
|
1850
|
-
if (!Number.isFinite(seconds) || seconds <= 0) return 0
|
|
1851
|
-
return Math.min(300, Math.trunc(seconds))
|
|
1852
|
-
}
|
|
1853
|
-
const control = createControlPlane({
|
|
1854
|
-
port: cfg.controlPort,
|
|
1855
|
-
stateRoot: store.root,
|
|
1856
|
-
version: pkg.version,
|
|
1857
|
-
log,
|
|
1858
|
-
actions: {
|
|
1859
|
-
// Liveness only: a probe must not sweep or reclaim runs, so this
|
|
1860
|
-
// deliberately does no state-directory work. Use GET /runs to ask what
|
|
1861
|
-
// is running.
|
|
1862
|
-
async health() {
|
|
1863
|
-
return { runs: 'GET /runs' }
|
|
1864
|
-
},
|
|
1865
|
-
async list({ limit } = {}) {
|
|
1866
|
-
await ready
|
|
1867
|
-
if (stateError) throw stateError
|
|
1868
|
-
const runs = await orchestrator.list()
|
|
1869
|
-
const stats = typeof store.stats === 'function' ? await store.stats() : null
|
|
1870
|
-
const rows = Math.max(1, Math.min(100, Number(limit) || 20))
|
|
1871
|
-
const visible = runs.slice(0, rows)
|
|
1872
|
-
return {
|
|
1873
|
-
data: { runs: visible, stats: stats ? { ...stats, root: store.root } : null },
|
|
1874
|
-
text: formatList(runs, rows, stats ? { ...stats, root: store.root } : null),
|
|
1875
|
-
}
|
|
1876
|
-
},
|
|
1877
|
-
async status(runId, waitSeconds) {
|
|
1878
|
-
await ready
|
|
1879
|
-
if (stateError) throw stateError
|
|
1880
|
-
const run = await orchestrator.status(String(runId ?? '').trim(), clampControlWait(waitSeconds))
|
|
1881
|
-
return { data: { run }, text: formatRun(run) }
|
|
1882
|
-
},
|
|
1883
|
-
async start(body = {}) {
|
|
1884
|
-
await ready
|
|
1885
|
-
if (stateError) throw stateError
|
|
1886
|
-
if (!hasSubagents()) {
|
|
1887
|
-
throw new Error(
|
|
1888
|
-
'subagent service is unavailable; dsh-superagent needs the host subagents service to create planner, '
|
|
1889
|
-
+ 'worker, and aggregator agents. Enable it in this profile (the base bundle provides it) and restart.',
|
|
1890
|
-
)
|
|
1891
|
-
}
|
|
1892
|
-
const goal = typeof body.goal === 'string' ? body.goal.trim() : ''
|
|
1893
|
-
if (!goal) {
|
|
1894
|
-
// Report the caller's mistake as written in the docs: a missing goal
|
|
1895
|
-
// is 400, not "you also did not name a session".
|
|
1896
|
-
throw new Error('goal is required; pass a concrete goal string')
|
|
1897
|
-
}
|
|
1898
|
-
const agent = resolveSession(body.session_id)
|
|
1899
|
-
const run = await orchestrator.start({
|
|
1900
|
-
goal,
|
|
1901
|
-
parentSessionId: agent.id,
|
|
1902
|
-
parent: agent,
|
|
1903
|
-
clientTimeZone: body.time_zone,
|
|
1904
|
-
allowDuplicate: body.allow_duplicate === true,
|
|
1905
|
-
mode: body.mode,
|
|
1906
|
-
queue: body.queue === true,
|
|
1907
|
-
approvePolicy: body.approve_policy === true,
|
|
1908
|
-
overrides: {
|
|
1909
|
-
maxSubtasks: body.max_subtasks,
|
|
1910
|
-
maxParallel: body.max_parallel,
|
|
1911
|
-
deadlineMinutes: body.deadline_minutes,
|
|
1912
|
-
},
|
|
1913
|
-
})
|
|
1914
|
-
const waitSeconds = clampControlWait(body.wait_seconds)
|
|
1915
|
-
if (waitSeconds > 0) {
|
|
1916
|
-
const finished = await orchestrator.status(run.id, waitSeconds)
|
|
1917
|
-
const current = run.deduped ? { ...finished, deduped: true } : finished
|
|
1918
|
-
return { data: { run: current }, text: formatRun(current) }
|
|
1919
|
-
}
|
|
1920
|
-
if (run.queue?.waiting) {
|
|
1921
|
-
return {
|
|
1922
|
-
data: { run },
|
|
1923
|
-
text: `${formatRun(run, { includeReport: false })}\n\nQueued, not started: it begins automatically when `
|
|
1924
|
-
+ `an active run finishes. Poll GET /runs/${run.id} or cancel it.`,
|
|
1925
|
-
}
|
|
1926
|
-
}
|
|
1927
|
-
return {
|
|
1928
|
-
data: { run },
|
|
1929
|
-
text: `${formatRun(run, { includeReport: false })}\n\nStarted in the background. Poll `
|
|
1930
|
-
+ `GET /runs/${run.id} or call superagent_status.`,
|
|
1931
|
-
}
|
|
1932
|
-
},
|
|
1933
|
-
async cancel(runId) {
|
|
1934
|
-
await ready
|
|
1935
|
-
if (stateError) throw stateError
|
|
1936
|
-
const run = await orchestrator.cancel(String(runId ?? '').trim())
|
|
1937
|
-
const head = run.status === 'cancelled'
|
|
1938
|
-
? `cancelled ${run.id}`
|
|
1939
|
-
: run.cancelPending
|
|
1940
|
-
? `cancel requested for ${run.id}, not confirmed by the owning process yet`
|
|
1941
|
-
: `${run.id} is ${run.status}; nothing to cancel`
|
|
1942
|
-
return { data: { run }, text: `${head}\n\n${formatRun(run, { includeReport: false })}` }
|
|
1943
|
-
},
|
|
1944
|
-
async resume(runId, body = {}) {
|
|
1945
|
-
await ready
|
|
1946
|
-
if (stateError) throw stateError
|
|
1947
|
-
if (!hasSubagents()) {
|
|
1948
|
-
throw new Error('subagent service is unavailable; resuming a run needs the host subagents service to create child agents.')
|
|
1949
|
-
}
|
|
1950
|
-
const agent = resolveSession(body.session_id)
|
|
1951
|
-
const run = await orchestrator.resume(
|
|
1952
|
-
String(runId ?? '').trim(),
|
|
1953
|
-
agent,
|
|
1954
|
-
body.time_zone,
|
|
1955
|
-
{ force: body.force === true || body.override_quota === true, approvePolicy: body.approve_policy === true },
|
|
1956
|
-
)
|
|
1957
|
-
const waitSeconds = clampControlWait(body.wait_seconds)
|
|
1958
|
-
const current = waitSeconds > 0 ? await orchestrator.status(run.id, waitSeconds) : run
|
|
1959
|
-
return { data: { run: current }, text: formatRun(current) }
|
|
1960
|
-
},
|
|
1961
|
-
},
|
|
1962
|
-
})
|
|
1963
|
-
let disposed = false
|
|
1964
|
-
const stopControl = () => {
|
|
1965
|
-
disposed = true
|
|
1966
|
-
return control.stop().catch(error => log(`cannot stop the control plane: ${error?.message ?? error}`))
|
|
1967
|
-
}
|
|
1968
|
-
if (typeof ctx.effect === 'function') {
|
|
1969
|
-
ctx.effect(() => stopControl, 'dsh-superagent control plane')
|
|
1970
|
-
} else if (typeof ctx.on === 'function') {
|
|
1971
|
-
ctx.on('dispose', stopControl)
|
|
1972
|
-
}
|
|
1973
|
-
// The state directory is created by `orchestrator.recover()`, which `ready`
|
|
1974
|
-
// awaits. Starting before it exists makes the discovery write fail with
|
|
1975
|
-
// ENOENT and would leave the plane off for the whole host lifetime.
|
|
1976
|
-
ready
|
|
1977
|
-
.then(() => {
|
|
1978
|
-
if (disposed || stateError) return null
|
|
1979
|
-
return control.start()
|
|
1980
|
-
})
|
|
1981
|
-
.catch(error => {
|
|
1982
|
-
log(
|
|
1983
|
-
`control plane is not listening: ${error?.message ?? error}; `
|
|
1984
|
-
+ 'check that controlPort is free and the state directory is writable, '
|
|
1985
|
-
+ 'or remove controlPort to keep the socket closed',
|
|
1986
|
-
)
|
|
1987
|
-
})
|
|
1988
|
-
}
|
|
1989
|
-
|
|
1990
|
-
// The workspace panel is opt-in for the same reason: mounting the plugin
|
|
1991
|
-
// must not open a socket. It reads and writes files itself, so the only
|
|
1992
|
-
// boundary that matters is the configured root, enforced in workbench.js.
|
|
1993
|
-
if (cfg.workbenchPort !== null) {
|
|
1994
|
-
const workbench = createWorkbench({
|
|
1995
|
-
port: cfg.workbenchPort,
|
|
1996
|
-
root: workbenchRoot,
|
|
1997
|
-
stateRoot: store.root,
|
|
1998
|
-
store,
|
|
1999
|
-
version: pkg.version,
|
|
2000
|
-
log,
|
|
2001
|
-
})
|
|
2002
|
-
let panelDisposed = false
|
|
2003
|
-
const stopWorkbench = () => {
|
|
2004
|
-
panelDisposed = true
|
|
2005
|
-
return workbench.stop().catch(error => log(`cannot stop the workbench: ${error?.message ?? error}`))
|
|
2006
|
-
}
|
|
2007
|
-
if (typeof ctx.effect === 'function') {
|
|
2008
|
-
ctx.effect(() => stopWorkbench, 'dsh-superagent workbench')
|
|
2009
|
-
} else if (typeof ctx.on === 'function') {
|
|
2010
|
-
ctx.on('dispose', stopWorkbench)
|
|
2011
|
-
}
|
|
2012
|
-
ready
|
|
2013
|
-
.then(() => {
|
|
2014
|
-
if (panelDisposed || stateError) return null
|
|
2015
|
-
return workbench.start()
|
|
2016
|
-
})
|
|
2017
|
-
.catch(error => {
|
|
2018
|
-
log(
|
|
2019
|
-
`workbench is not listening: ${error?.message ?? error}; `
|
|
2020
|
-
+ `check that workbenchRoot (${workbenchRoot}) exists, that workbenchPort is free, and that the state `
|
|
2021
|
-
+ 'directory is writable, or remove workbenchPort to keep the panel off',
|
|
2022
|
-
)
|
|
2023
|
-
})
|
|
2024
|
-
}
|
|
2025
|
-
|
|
2026
|
-
log(
|
|
2027
|
-
`registered ${auditor ? 11 : 10} tools; state ${store.root}`
|
|
2028
|
-
+ `${cfg.controlPort === null ? '' : `; control port ${cfg.controlPort}`}`
|
|
2029
|
-
+ `${cfg.workbenchPort === null ? '' : `; workbench ${workbenchRoot} on port ${cfg.workbenchPort}`}`,
|
|
2030
|
-
)
|
|
2031
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* dsh-superagent — long-horizon autonomous runs for DeepSeek Harness.
|
|
3
|
+
*
|
|
4
|
+
* One goal enters; a planner decomposes it into subtasks; independent subtasks
|
|
5
|
+
* run in parallel child agents while a declared dependency holds the rest back;
|
|
6
|
+
* an aggregator merges their reports. Runs survive a host restart, can be
|
|
7
|
+
* cancelled, and have their token usage read back from the child sessions'
|
|
8
|
+
* durable logs.
|
|
9
|
+
*
|
|
10
|
+
* Registered tools: superagent_start, superagent_status, superagent_list,
|
|
11
|
+
* superagent_cancel, superagent_resume, superagent_followup, superagent_inject,
|
|
12
|
+
* superagent_answer, superagent_memory, superagent_template, superagent_audit.
|
|
13
|
+
*
|
|
14
|
+
* @module dsh-superagent
|
|
15
|
+
*/
|
|
16
|
+
import { randomUUID } from 'node:crypto'
|
|
17
|
+
import { existsSync } from 'node:fs'
|
|
18
|
+
import os from 'node:os'
|
|
19
|
+
import path from 'node:path'
|
|
20
|
+
import { fileURLToPath } from 'node:url'
|
|
21
|
+
import pkg from '../package.json' with { type: 'json' }
|
|
22
|
+
import { createAuditor } from './audit.js'
|
|
23
|
+
import { createOrchestrator, followupEffect } from './orchestrator.js'
|
|
24
|
+
import { createChildSteerer, createChildWatcher, INJECT_POLL_MS, pendingIds } from './inject.js'
|
|
25
|
+
import { createControlPlane } from './control.js'
|
|
26
|
+
import { formatMoney } from './cost.js'
|
|
27
|
+
import { createGuard } from './guard.js'
|
|
28
|
+
import { classifyError, describeError, summarizeError } from './errors.js'
|
|
29
|
+
import { createLedger } from './ledger.js'
|
|
30
|
+
import { createMemory, isInside, MEMORY_KINDS, normalizeScope } from './memory.js'
|
|
31
|
+
import { createNotifyPolicy, createOutbox } from './notify.js'
|
|
32
|
+
import { ACTIVE_STATUSES, createStore, resolveStateRoot, TERMINAL_STATUSES } from './store.js'
|
|
33
|
+
import { createTemplateStore, expandTemplate, formatTemplateDetail, formatTemplateList, TemplateError } from './templates.js'
|
|
34
|
+
import { createUsageReader } from './usage.js'
|
|
35
|
+
import { describeWorkspace } from './workspace.js'
|
|
36
|
+
import { createRunChangeTracker, createWorkbench } from './workbench.js'
|
|
37
|
+
|
|
38
|
+
export const name = 'dsh-superagent'
|
|
39
|
+
// The host menu and sessions are required. `subagents` is read through
|
|
40
|
+
// `ctx.get('subagents')`, so a profile without it still mounts the eleven tools;
|
|
41
|
+
// they then report what is missing instead of the plugin silently vanishing.
|
|
42
|
+
export const inject = ['tools', 'agents']
|
|
43
|
+
|
|
44
|
+
const DEFAULTS = {
|
|
45
|
+
/** Directory for run state; defaults to `$DSH_HOME/state/superagent`. */
|
|
46
|
+
stateDir: null,
|
|
47
|
+
/** Child backend registered on `ctx.subagents`. */
|
|
48
|
+
provider: 'spawn',
|
|
49
|
+
/** Optional provider override for every child agent; unset inherits the parent's model route. */
|
|
50
|
+
childProvider: null,
|
|
51
|
+
/** Optional model override for every child agent; unset inherits the parent's model. */
|
|
52
|
+
childModel: null,
|
|
53
|
+
/**
|
|
54
|
+
* Optional agent preset for child agents. A preset owns the child's tool
|
|
55
|
+
* composition, which is the only way this host version can restrict it.
|
|
56
|
+
*/
|
|
57
|
+
childPreset: null,
|
|
58
|
+
/**
|
|
59
|
+
* Delegation depth granted to child agents. 1 means a worker may not create
|
|
60
|
+
* children of its own; `provider-managed` leaves the cap to the backend.
|
|
61
|
+
*/
|
|
62
|
+
maxSubagentDepth: 1,
|
|
63
|
+
/** Upper bound on planned subtasks per run. */
|
|
64
|
+
maxSubtasks: 8,
|
|
65
|
+
/** Upper bound on subtasks executing at once. */
|
|
66
|
+
maxParallel: 3,
|
|
67
|
+
/** Runs allowed to be active at the same time; a start over this waits instead of failing. */
|
|
68
|
+
maxActiveRuns: 2,
|
|
69
|
+
/** Runs allowed to wait for a free slot when queueing is on; 0 disables queueing. */
|
|
70
|
+
maxQueuedRuns: 5,
|
|
71
|
+
/** How long a queued run waits before it fails, in minutes. */
|
|
72
|
+
queueTimeoutMinutes: 30,
|
|
73
|
+
/**
|
|
74
|
+
* Queue starts that did not ask for it with `queue: true`. Off by default: a
|
|
75
|
+
* caller opts in, so a script that relied on the quota error keeps seeing it.
|
|
76
|
+
*/
|
|
77
|
+
queueOnFull: false,
|
|
78
|
+
/** Attempts per subtask before it is marked failed. */
|
|
79
|
+
attempts: 2,
|
|
80
|
+
/** Wall-clock budget for a whole run, in minutes. */
|
|
81
|
+
deadlineMinutes: 120,
|
|
82
|
+
/** Hard cap on child model calls per run; 0 disables the cap. */
|
|
83
|
+
maxModelCallsPerRun: 80,
|
|
84
|
+
/** Hard cap on prompt + completion tokens per run; 0 disables the cap. */
|
|
85
|
+
maxTokensPerRun: 2_000_000,
|
|
86
|
+
/**
|
|
87
|
+
* List prices per 1M tokens, keyed by model id as it appears in usage logs.
|
|
88
|
+
* Only models listed here are priced; everything else is reported as unpriced
|
|
89
|
+
* rather than guessed. Nothing is shipped: a stale price is worse than none.
|
|
90
|
+
*/
|
|
91
|
+
pricing: {},
|
|
92
|
+
/** Bytes kept from one subtask report. */
|
|
93
|
+
resultCapBytes: 32 * 1024,
|
|
94
|
+
/** Write one message back to the owning session when a run finishes unattended. */
|
|
95
|
+
notifyOnComplete: true,
|
|
96
|
+
/**
|
|
97
|
+
* Proactive messages allowed per rolling hour. Runs that finish after the cap
|
|
98
|
+
* are folded into one summary instead of waking the session again.
|
|
99
|
+
*/
|
|
100
|
+
maxNotificationsPerHour: 3,
|
|
101
|
+
/**
|
|
102
|
+
* Extra rounds that retry failed subtasks before the failure is reported, so
|
|
103
|
+
* a transient error is healed automatically instead of asking the user.
|
|
104
|
+
*/
|
|
105
|
+
autoResumeRounds: 1,
|
|
106
|
+
/**
|
|
107
|
+
* Delivery attempts for one wake-up. A followup can fail while the session
|
|
108
|
+
* loop is busy; retrying it is the difference between a lost result and a
|
|
109
|
+
* late one. 0 means one attempt.
|
|
110
|
+
*/
|
|
111
|
+
notifyRetries: 2,
|
|
112
|
+
/** First delay between delivery attempts; it doubles per attempt. */
|
|
113
|
+
notifyRetryDelayMs: 2000,
|
|
114
|
+
/**
|
|
115
|
+
* Poll period, in milliseconds, used to observe when a running child claims
|
|
116
|
+
* an injected message. It is the resolution of every reported latency, so it
|
|
117
|
+
* is deliberately visible instead of rounded away.
|
|
118
|
+
*/
|
|
119
|
+
injectPollMs: INJECT_POLL_MS,
|
|
120
|
+
/**
|
|
121
|
+
* Child model used on a self-heal round when the failure looks transient
|
|
122
|
+
* (quota, rate limit, timeout). `null` keeps the configured route.
|
|
123
|
+
*/
|
|
124
|
+
childModelFallback: null,
|
|
125
|
+
/**
|
|
126
|
+
* Cross-run notebook. Notes live under `stateDir` and never enter the package
|
|
127
|
+
* or a default commit; see the privacy section of the README.
|
|
128
|
+
*/
|
|
129
|
+
memory: true,
|
|
130
|
+
/** Notebook scope; each scope is one file, so unrelated projects stay apart. */
|
|
131
|
+
memoryScope: 'default',
|
|
132
|
+
/** Notes kept before the notebook is compacted. */
|
|
133
|
+
memoryMaxEntries: 60,
|
|
134
|
+
/** Notes older than this are ignored, then compacted away. */
|
|
135
|
+
memoryMaxAgeDays: 30,
|
|
136
|
+
/** Notes injected into the planner and aggregator prompts. */
|
|
137
|
+
memoryDigestEntries: 12,
|
|
138
|
+
/** Character budget for the note part of that prompt context. */
|
|
139
|
+
memoryDigestChars: 1600,
|
|
140
|
+
/** Delete terminal runs older than this many days on mount; 0 keeps everything. */
|
|
141
|
+
keepRuns: 0,
|
|
142
|
+
/**
|
|
143
|
+
* Safety guard for child tool calls. Workers inherit the session's filesystem
|
|
144
|
+
* and credentials, so this policy is enforced on the host's tool pipeline.
|
|
145
|
+
* Defaults stand in `lib/guard.js`; see “Safety guard” in the README.
|
|
146
|
+
*/
|
|
147
|
+
guard: {
|
|
148
|
+
enabled: true,
|
|
149
|
+
/** Extra writable roots; the child session workspace and OS temp dir are implicit. */
|
|
150
|
+
allowWriteRoots: [],
|
|
151
|
+
/** Extra paths denied for both reading and writing. */
|
|
152
|
+
denyPaths: [],
|
|
153
|
+
/** Extra `{ id, pattern, reason }` command denials. */
|
|
154
|
+
denyCommands: [],
|
|
155
|
+
/** `{ id, pattern, reason }` entries that override a denial; every use is recorded. */
|
|
156
|
+
allowCommands: [],
|
|
157
|
+
/** Events kept per run; the counters still include events beyond the cap. */
|
|
158
|
+
maxEvents: 50,
|
|
159
|
+
},
|
|
160
|
+
/**
|
|
161
|
+
* Append-only audit trail under `<stateDir>/audit/audit.jsonl`. It is an
|
|
162
|
+
* observer layer: turning it off removes the trail, never the run behaviour.
|
|
163
|
+
*/
|
|
164
|
+
audit: true,
|
|
165
|
+
/**
|
|
166
|
+
* Permission policy for runs. Unset means `<stateDir>/policy.json` when that
|
|
167
|
+
* file exists, so dropping a policy next to the state is enough to enable it.
|
|
168
|
+
* An empty state means "no policy", which is exactly the old behaviour.
|
|
169
|
+
*/
|
|
170
|
+
policyFile: null,
|
|
171
|
+
/** Where the audit JSONL lives; defaults to `<stateDir>/audit`. */
|
|
172
|
+
auditDir: null,
|
|
173
|
+
/**
|
|
174
|
+
* Loopback HTTP port for the embedding surface. `null` (default) keeps the
|
|
175
|
+
* socket closed; `0` asks the OS for a free port. The bound address and its
|
|
176
|
+
* bearer token are written to `<stateDir>/control.json`.
|
|
177
|
+
*/
|
|
178
|
+
controlPort: null,
|
|
179
|
+
/**
|
|
180
|
+
* Run every worker in its own git worktree of `workspaceRoot`, so parallel
|
|
181
|
+
* workers cannot overwrite each other's files. Off by default: it needs a
|
|
182
|
+
* git repository and it moves files, which is not something a plugin should
|
|
183
|
+
* start doing unasked.
|
|
184
|
+
*/
|
|
185
|
+
workspaceIsolation: false,
|
|
186
|
+
/** Repository whose worktrees isolate the workers; defaults to the host's cwd. */
|
|
187
|
+
workspaceRoot: null,
|
|
188
|
+
/**
|
|
189
|
+
* Loopback HTTP port for the local workspace panel. `null` (default) keeps it
|
|
190
|
+
* off; `0` asks the OS for a free port. The bound address and its one-time
|
|
191
|
+
* token are written to `<stateDir>/workbench.json`.
|
|
192
|
+
*/
|
|
193
|
+
workbenchPort: null,
|
|
194
|
+
/**
|
|
195
|
+
* Directory the panel may read and edit. Everything outside it is refused.
|
|
196
|
+
* Defaults to the host process's working directory.
|
|
197
|
+
*/
|
|
198
|
+
workbenchRoot: null,
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const REPORT_PREVIEW_CHARS = 8000
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Coerce one numeric setting into its documented range. A value like "abc"
|
|
205
|
+
* would otherwise become NaN and silently remove a limit (NaN comparisons are
|
|
206
|
+
* always false), which is how a quota disappears without any error.
|
|
207
|
+
*/
|
|
208
|
+
function bounded(value, fallback, min, max) {
|
|
209
|
+
const number = Number(value)
|
|
210
|
+
if (!Number.isFinite(number)) return fallback
|
|
211
|
+
return Math.min(max, Math.max(min, Math.trunc(number)))
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* A port is a whole number in 0–65535, or nothing. A malformed value must not
|
|
216
|
+
* silently open a socket somewhere unexpected, so anything else stays off.
|
|
217
|
+
*/
|
|
218
|
+
function controlPortOf(value) {
|
|
219
|
+
if (value === null || value === undefined || value === false) return null
|
|
220
|
+
// Coercion would turn "" and " " into 0, i.e. an accidental listener; only a
|
|
221
|
+
// real number or a plain digit string may enable the surface.
|
|
222
|
+
if (typeof value === 'number') {
|
|
223
|
+
return Number.isInteger(value) && value >= 0 && value <= 65535 ? value : null
|
|
224
|
+
}
|
|
225
|
+
if (typeof value === 'string' && /^\d+$/.test(value.trim())) {
|
|
226
|
+
const number = Number(value.trim())
|
|
227
|
+
return number <= 65535 ? number : null
|
|
228
|
+
}
|
|
229
|
+
return null
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** Read a YAML/JSON boolean without letting the string "false" mean true. */
|
|
233
|
+
function flag(value, fallback) {
|
|
234
|
+
if (value === undefined) return fallback
|
|
235
|
+
if (typeof value === 'string') return !/^(false|0|off|no)$/i.test(value.trim())
|
|
236
|
+
return Boolean(value)
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function resolveConfig(config) {
|
|
240
|
+
const merged = { ...DEFAULTS }
|
|
241
|
+
if (config && typeof config === 'object') {
|
|
242
|
+
for (const [key, value] of Object.entries(config)) {
|
|
243
|
+
if (value !== undefined) merged[key] = value
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
merged.maxSubtasks = bounded(merged.maxSubtasks, DEFAULTS.maxSubtasks, 1, 16)
|
|
247
|
+
merged.maxParallel = bounded(merged.maxParallel, DEFAULTS.maxParallel, 1, 8)
|
|
248
|
+
merged.maxActiveRuns = bounded(merged.maxActiveRuns, DEFAULTS.maxActiveRuns, 1, 8)
|
|
249
|
+
merged.maxQueuedRuns = bounded(merged.maxQueuedRuns, DEFAULTS.maxQueuedRuns, 0, 32)
|
|
250
|
+
merged.queueTimeoutMinutes = bounded(merged.queueTimeoutMinutes, DEFAULTS.queueTimeoutMinutes, 1, 720)
|
|
251
|
+
merged.queueOnFull = flag(merged.queueOnFull, DEFAULTS.queueOnFull)
|
|
252
|
+
merged.attempts = bounded(merged.attempts, DEFAULTS.attempts, 1, 5)
|
|
253
|
+
merged.deadlineMinutes = bounded(merged.deadlineMinutes, DEFAULTS.deadlineMinutes, 1, 720)
|
|
254
|
+
merged.maxModelCallsPerRun = bounded(merged.maxModelCallsPerRun, DEFAULTS.maxModelCallsPerRun, 0, 10000)
|
|
255
|
+
merged.maxTokensPerRun = bounded(merged.maxTokensPerRun, DEFAULTS.maxTokensPerRun, 0, 1e12)
|
|
256
|
+
merged.resultCapBytes = bounded(merged.resultCapBytes, DEFAULTS.resultCapBytes, 1024, 1024 * 1024)
|
|
257
|
+
merged.keepRuns = bounded(merged.keepRuns, DEFAULTS.keepRuns, 0, 3650)
|
|
258
|
+
merged.controlPort = controlPortOf(merged.controlPort)
|
|
259
|
+
merged.workbenchPort = controlPortOf(merged.workbenchPort)
|
|
260
|
+
merged.workbenchRoot = typeof merged.workbenchRoot === 'string' && merged.workbenchRoot.trim()
|
|
261
|
+
? merged.workbenchRoot.trim()
|
|
262
|
+
: null
|
|
263
|
+
merged.maxSubagentDepth = merged.maxSubagentDepth === 'provider-managed'
|
|
264
|
+
? 'provider-managed'
|
|
265
|
+
: bounded(merged.maxSubagentDepth, DEFAULTS.maxSubagentDepth, 0, 4)
|
|
266
|
+
// Per-model prices merge, so a user can add one route without restating the
|
|
267
|
+
// built-in table.
|
|
268
|
+
merged.pricing = { ...DEFAULTS.pricing, ...(config?.pricing ?? {}) }
|
|
269
|
+
merged.memory = flag(merged.memory, DEFAULTS.memory)
|
|
270
|
+
merged.audit = flag(merged.audit, DEFAULTS.audit)
|
|
271
|
+
merged.policyFile = typeof merged.policyFile === 'string' && merged.policyFile.trim()
|
|
272
|
+
? merged.policyFile.trim()
|
|
273
|
+
: null
|
|
274
|
+
merged.auditDir = typeof merged.auditDir === 'string' && merged.auditDir.trim()
|
|
275
|
+
? merged.auditDir.trim()
|
|
276
|
+
: null
|
|
277
|
+
merged.memoryScope = normalizeScope(merged.memoryScope)
|
|
278
|
+
merged.memoryMaxEntries = bounded(merged.memoryMaxEntries, DEFAULTS.memoryMaxEntries, 1, 500)
|
|
279
|
+
merged.memoryMaxAgeDays = bounded(merged.memoryMaxAgeDays, DEFAULTS.memoryMaxAgeDays, 1, 3650)
|
|
280
|
+
merged.memoryDigestEntries = bounded(merged.memoryDigestEntries, DEFAULTS.memoryDigestEntries, 1, 50)
|
|
281
|
+
merged.memoryDigestChars = bounded(merged.memoryDigestChars, DEFAULTS.memoryDigestChars, 200, 8000)
|
|
282
|
+
merged.autoResumeRounds = bounded(merged.autoResumeRounds, DEFAULTS.autoResumeRounds, 0, 3)
|
|
283
|
+
merged.notifyRetries = bounded(merged.notifyRetries, DEFAULTS.notifyRetries, 0, 5)
|
|
284
|
+
merged.notifyRetryDelayMs = bounded(merged.notifyRetryDelayMs, DEFAULTS.notifyRetryDelayMs, 0, 60000)
|
|
285
|
+
merged.injectPollMs = bounded(merged.injectPollMs, DEFAULTS.injectPollMs, 10, 1000)
|
|
286
|
+
merged.maxNotificationsPerHour = bounded(merged.maxNotificationsPerHour, DEFAULTS.maxNotificationsPerHour, 0, 1000)
|
|
287
|
+
merged.childModelFallback = typeof merged.childModelFallback === 'string' && merged.childModelFallback.trim()
|
|
288
|
+
? merged.childModelFallback.trim()
|
|
289
|
+
: null
|
|
290
|
+
merged.workspaceIsolation = flag(merged.workspaceIsolation, DEFAULTS.workspaceIsolation)
|
|
291
|
+
// A blank path would resolve to the cwd, which is how isolation would silently
|
|
292
|
+
// point at the wrong repository; blank therefore means "use the default".
|
|
293
|
+
merged.workspaceRoot = typeof merged.workspaceRoot === 'string' && merged.workspaceRoot.trim()
|
|
294
|
+
? merged.workspaceRoot.trim()
|
|
295
|
+
: null
|
|
296
|
+
// The guard block merges so a user can set only `allowCommands` without
|
|
297
|
+
// restating the rest of the defaults.
|
|
298
|
+
merged.guard = {
|
|
299
|
+
...DEFAULTS.guard,
|
|
300
|
+
...(config?.guard && typeof config.guard === 'object' ? config.guard : {}),
|
|
301
|
+
}
|
|
302
|
+
return merged
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
function preview(text, limit = REPORT_PREVIEW_CHARS) {
|
|
306
|
+
if (typeof text !== 'string') return ''
|
|
307
|
+
if (text.length <= limit) return text
|
|
308
|
+
return `${text.slice(0, limit)}\n\n[report truncated to ${limit} characters; full text is in the run state file]`
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function durationText(ms) {
|
|
312
|
+
const seconds = Math.max(0, ms / 1000)
|
|
313
|
+
if (seconds < 60) return `${seconds.toFixed(1)}s`
|
|
314
|
+
const minutes = Math.floor(seconds / 60)
|
|
315
|
+
return `${minutes}m ${Math.round(seconds - minutes * 60)}s`
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
function elapsed(run) {
|
|
319
|
+
const start = Date.parse(run.startedAt)
|
|
320
|
+
const end = run.finishedAt ? Date.parse(run.finishedAt) : Date.now()
|
|
321
|
+
if (!Number.isFinite(start) || !Number.isFinite(end)) return 'unknown'
|
|
322
|
+
const wall = Math.max(0, end - start)
|
|
323
|
+
const active = Number.isFinite(run.activeMs) ? run.activeMs : wall
|
|
324
|
+
// A resumed run can span hours of downtime. Reporting one number would make
|
|
325
|
+
// it look like the model worked all that time.
|
|
326
|
+
if (run.resumedAt && wall - active > 5000) {
|
|
327
|
+
return `${durationText(active)} running, ${durationText(wall)} since it was started (includes time stopped)`
|
|
328
|
+
}
|
|
329
|
+
return durationText(wall)
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
function usageLine(usage, status) {
|
|
333
|
+
if (!usage || !usage.modelCalls) {
|
|
334
|
+
if (ACTIVE_STATUSES.has(status)) {
|
|
335
|
+
return 'usage: accounting pending — token usage is read from child session logs while the run is in progress'
|
|
336
|
+
}
|
|
337
|
+
return 'usage: not recorded — no child session log was readable for this run '
|
|
338
|
+
+ '(usually a run created before usage tracking, or a sessions directory that moved); '
|
|
339
|
+
+ 'token and cost figures are unavailable'
|
|
340
|
+
}
|
|
341
|
+
const models = Object.entries(usage.models ?? {})
|
|
342
|
+
.map(([model, entry]) => `${model}: ${entry.calls} call(s) ${entry.inputTokens} in / ${entry.outputTokens} out`)
|
|
343
|
+
.join('; ')
|
|
344
|
+
const cached = usage.cacheReadTokens ? ` (+${usage.cacheReadTokens} prompt tokens served from cache)` : ''
|
|
345
|
+
return `usage: input ${usage.inputTokens}${cached}, output ${usage.outputTokens}, calls ${usage.modelCalls}`
|
|
346
|
+
+ (models ? ` (${models})` : '')
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* Cost line for one run. The number is an estimate from the configured list
|
|
351
|
+
* prices; models without a price are named instead of guessed so a user can
|
|
352
|
+
* always tell how much of the spend the figure covers.
|
|
353
|
+
*/
|
|
354
|
+
function costLine(run) {
|
|
355
|
+
if (!run.usage || !run.usage.modelCalls) return null
|
|
356
|
+
const models = Object.keys(run.usage.models ?? {})
|
|
357
|
+
const cost = run.cost
|
|
358
|
+
// An all-unpriced run has no priced line at all. Printing 0.0000 there would
|
|
359
|
+
// claim the run was free, which is the one thing an estimate must not do.
|
|
360
|
+
const priced = Boolean(cost) && Object.keys(cost.byModel ?? {}).length > 0
|
|
361
|
+
if (!priced) {
|
|
362
|
+
const named = cost?.unpriced?.length ? cost.unpriced.join(', ') : (models.join(', ') || 'this model')
|
|
363
|
+
return `cost: not computed — no price configured for ${named}; `
|
|
364
|
+
+ 'add a pricing entry in cordis.patch.yml to get an estimate'
|
|
365
|
+
}
|
|
366
|
+
const money = formatMoney(cost)
|
|
367
|
+
if (cost.complete) return `cost: ${money} (estimate; all models priced)`
|
|
368
|
+
return `cost: at least ${money} (estimate; no price for ${cost.unpriced.join(', ')})`
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/** Spend for one subtask: measured when priced, explicit when not. */
|
|
372
|
+
function subtaskCostText(subtask) {
|
|
373
|
+
if (!subtask?.usage || !subtask.usage.modelCalls) return ''
|
|
374
|
+
const cost = subtask.cost
|
|
375
|
+
if (!cost || Object.keys(cost.byModel ?? {}).length === 0) {
|
|
376
|
+
const named = cost?.unpriced?.length ? ` (${cost.unpriced.join(', ')})` : ''
|
|
377
|
+
return `, cost unpriced${named}`
|
|
378
|
+
}
|
|
379
|
+
return `, ${formatMoney(cost)}${cost.complete ? '' : '+'}`
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/** Render one run as text for a tool result. */
|
|
383
|
+
function formatRun(run, { includeReport = true } = {}) {
|
|
384
|
+
const completed = run.subtasks.filter(subtask => subtask.status === 'completed').length
|
|
385
|
+
const lines = [
|
|
386
|
+
`run ${run.id} — ${run.status}`,
|
|
387
|
+
`goal: ${run.goal}`,
|
|
388
|
+
`plan: ${run.plan?.mode ?? 'pending'}; subtasks ${completed}/${run.subtasks.length} completed; `
|
|
389
|
+
+ `max ${run.limits.maxParallel} in parallel; ${run.limits.attempts} attempt(s) each`,
|
|
390
|
+
`elapsed: ${elapsed(run)}`,
|
|
391
|
+
usageLine(run.usage, run.status),
|
|
392
|
+
]
|
|
393
|
+
if (run.queue?.waiting) {
|
|
394
|
+
lines.push(
|
|
395
|
+
`queue: waiting for a free slot — position ${run.queue.position} of ${run.queue.of}; `
|
|
396
|
+
+ 'it starts automatically when an active run finishes, does not count against maxActiveRuns while it waits, '
|
|
397
|
+
+ `and fails if no slot frees by ${run.queue.timeoutAt}`,
|
|
398
|
+
)
|
|
399
|
+
} else if (run.queue?.expired) {
|
|
400
|
+
lines.push(`queue: timed out after waiting ${run.queue.of > 0 ? `behind ${run.queue.of} run(s)` : 'for a slot'}; it never started`)
|
|
401
|
+
} else if (run.queue?.cancelled) {
|
|
402
|
+
lines.push('queue: cancelled while waiting for a slot; it never started')
|
|
403
|
+
}
|
|
404
|
+
const unreadable = Object.keys(run.counters?.unreadable ?? {}).length
|
|
405
|
+
if (unreadable > 0) {
|
|
406
|
+
lines.push(
|
|
407
|
+
`usage note: ${unreadable} child session log(s) could not be read, so the token figures above cover only `
|
|
408
|
+
+ 'the readable ones; the model-call budget counted those children as one call each instead of ignoring them',
|
|
409
|
+
)
|
|
410
|
+
}
|
|
411
|
+
const cost = costLine(run)
|
|
412
|
+
if (cost) lines.push(cost)
|
|
413
|
+
if (run.memory?.digest) {
|
|
414
|
+
lines.push(
|
|
415
|
+
`memory: ${run.memory.notes} note(s) and ${run.memory.runs} earlier run(s) carried into this run `
|
|
416
|
+
+ `(${run.memory.digestChars} chars)`,
|
|
417
|
+
)
|
|
418
|
+
}
|
|
419
|
+
if (run.guard && (run.guard.blocked > 0 || run.guard.allowed > 0)) {
|
|
420
|
+
const rules = Object.entries(run.guard.byRule ?? {})
|
|
421
|
+
.map(([rule, count]) => `${rule} ×${count}`)
|
|
422
|
+
.join(', ')
|
|
423
|
+
lines.push(
|
|
424
|
+
`guard: ${run.guard.blocked} tool call(s) blocked; ${run.guard.allowed} explicit allow(s) recorded`
|
|
425
|
+
+ (rules ? ` (${rules})` : ''),
|
|
426
|
+
)
|
|
427
|
+
for (const event of (run.guard.events ?? []).filter(item => item.decision === 'blocked').slice(0, 3)) {
|
|
428
|
+
const detail = String(event.detail ?? '').replace(/\s+/g, ' ').slice(0, 120)
|
|
429
|
+
lines.push(` blocked ${event.tool}${event.label ? ` (${event.label})` : ''}: ${detail} — ${event.rule}`)
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
if (run.attention?.issue) {
|
|
433
|
+
lines.push(`attention: ${run.attention.issue}`)
|
|
434
|
+
}
|
|
435
|
+
if (run.attention?.items?.length > 0) {
|
|
436
|
+
const items = run.attention.items
|
|
437
|
+
const idOf = item => item.id ?? `q${items.indexOf(item) + 1}`
|
|
438
|
+
const open = items.filter(item => !item.answer)
|
|
439
|
+
const first = open[0] ?? items[0]
|
|
440
|
+
if (open.length > 0) {
|
|
441
|
+
lines.push(`needs your decision: ${first.question}${first.source ? ` (from ${first.source})` : ''}`)
|
|
442
|
+
if (first.options?.length) lines.push(`options: ${first.options.join(' | ')}`)
|
|
443
|
+
if (first.reason) lines.push(`why: ${first.reason}`)
|
|
444
|
+
lines.push(`attention id: ${idOf(first)}`)
|
|
445
|
+
} else {
|
|
446
|
+
// Answering does not hide the question: the record shows what was decided.
|
|
447
|
+
lines.push(`answered [${idOf(first)}]: ${first.question} — ${first.answer}`)
|
|
448
|
+
}
|
|
449
|
+
if (open.length > 1) {
|
|
450
|
+
lines.push(`and ${open.length - 1} more open question(s): ${open.slice(1).map(idOf).join(', ')}`)
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
if (Array.isArray(run.followups) && run.followups.length > 0) {
|
|
454
|
+
const pending = run.followups.filter(entry => !entry.appliedAt)
|
|
455
|
+
const missed = pending.filter(entry => entry.missedAt)
|
|
456
|
+
const applied = run.followups.length - pending.length
|
|
457
|
+
if (applied > 0) {
|
|
458
|
+
const stages = [...new Set(run.followups.filter(entry => entry.appliedAt).map(entry => entry.appliedAtStage))]
|
|
459
|
+
lines.push(`instructions: ${applied} added during the run, applied at ${stages.join(' / ')}`)
|
|
460
|
+
}
|
|
461
|
+
if (pending.length > missed.length) {
|
|
462
|
+
lines.push(
|
|
463
|
+
`instructions: ${pending.length - missed.length} waiting; they take effect at ${followupEffect(run).detail}`,
|
|
464
|
+
)
|
|
465
|
+
}
|
|
466
|
+
if (missed.length > 0) {
|
|
467
|
+
lines.push(
|
|
468
|
+
`instructions: ${missed.length} never took effect — ${missed[0].missedReason ?? 'the run settled first'}`,
|
|
469
|
+
)
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
if (Array.isArray(run.injections) && run.injections.length > 0) {
|
|
473
|
+
const degraded = run.injections.filter(entry => entry.status === 'degraded')
|
|
474
|
+
const targets = run.injections.flatMap(entry => entry.targets ?? [])
|
|
475
|
+
const applied = targets.filter(target => target.status === 'applied')
|
|
476
|
+
const pending = targets.filter(target => target.status === 'pending')
|
|
477
|
+
const missed = targets.filter(target => target.status === 'missed' || target.status === 'failed')
|
|
478
|
+
const worst = run.injectionStats?.worstLatencyMs
|
|
479
|
+
if (applied.length > 0) {
|
|
480
|
+
lines.push(
|
|
481
|
+
`live injections: ${applied.length} reached a child's next step`
|
|
482
|
+
+ (Number.isFinite(worst) ? ` (worst measured ${worst} ms)` : ''),
|
|
483
|
+
)
|
|
484
|
+
}
|
|
485
|
+
if (pending.length > 0) {
|
|
486
|
+
lines.push(`live injections: ${pending.length} accepted and waiting for a child's next step boundary`)
|
|
487
|
+
}
|
|
488
|
+
if (missed.length > 0) {
|
|
489
|
+
lines.push(
|
|
490
|
+
`live injections: ${missed.length} never entered a prompt — `
|
|
491
|
+
+ `${missed[0].missedReason ?? missed[0].error ?? 'the child left first'}`,
|
|
492
|
+
)
|
|
493
|
+
}
|
|
494
|
+
if (degraded.length > 0) {
|
|
495
|
+
lines.push(
|
|
496
|
+
`live injections: ${degraded.length} could not be delivered live and were queued; they take effect at `
|
|
497
|
+
+ followupEffect(run).detail,
|
|
498
|
+
)
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
if (Array.isArray(run.milestones) && run.milestones.length > 0) {
|
|
502
|
+
// Times are UTC because the record is ISO; a status line is not a place to
|
|
503
|
+
// start guessing the reader's timezone.
|
|
504
|
+
lines.push(`milestones: ${run.milestones
|
|
505
|
+
.map(milestone => `${milestone.name}@${String(milestone.at ?? '').slice(11, 19)}`)
|
|
506
|
+
.join(' → ')}`)
|
|
507
|
+
}
|
|
508
|
+
lines.push(...describeWorkspace(run.workspace))
|
|
509
|
+
const reportArtifact = (run.artifacts ?? []).find(artifact => artifact?.kind === 'report')
|
|
510
|
+
if (reportArtifact?.path) lines.push(`report file: ${reportArtifact.path} (${reportArtifact.bytes} bytes)`)
|
|
511
|
+
else if (run.artifactError) lines.push(`report file: not written — ${run.artifactError}`)
|
|
512
|
+
if (run.deduped) {
|
|
513
|
+
lines.push(
|
|
514
|
+
'deduped: true — an active run with the same goal already exists, so this call joined it instead of starting '
|
|
515
|
+
+ 'a second one (pass allow_duplicate: true to start another)',
|
|
516
|
+
)
|
|
517
|
+
}
|
|
518
|
+
if (run.selfHeal?.retried) {
|
|
519
|
+
lines.push(
|
|
520
|
+
`self-heal: retried ${run.selfHeal.retried} failed subtask(s) in ${run.selfHeal.rounds} extra round(s); `
|
|
521
|
+
+ `${run.selfHeal.recovered} recovered` + (run.selfHeal.model ? ` (on ${run.selfHeal.model})` : ''),
|
|
522
|
+
)
|
|
523
|
+
}
|
|
524
|
+
if (run.memoryWrite?.written > 0) {
|
|
525
|
+
lines.push(`memory: wrote ${run.memoryWrite.written} note(s) for the next run`)
|
|
526
|
+
} else if (run.memoryWrite?.reason && /^(the memory block|write failed)/.test(run.memoryWrite.reason)) {
|
|
527
|
+
lines.push(`memory note not written: ${run.memoryWrite.reason}`)
|
|
528
|
+
}
|
|
529
|
+
if (run.resumedAt) lines.push(`resumed at: ${run.resumedAt}`)
|
|
530
|
+
if (run.reclaimed) lines.push(`reclaimed: ${run.reclaimed.basis}`)
|
|
531
|
+
if (run.status === 'interrupted' && run.error) {
|
|
532
|
+
// Not a failure: the host went away and the run is waiting to be resumed.
|
|
533
|
+
lines.push(`note: ${run.error}`)
|
|
534
|
+
} else if (run.status !== 'cancelled' && run.error) {
|
|
535
|
+
lines.push(`error: ${summarizeError(run.error)}`)
|
|
536
|
+
if (run.status === 'failed') lines.push(`hint: ${classifyError(run.error).hint}`)
|
|
537
|
+
}
|
|
538
|
+
if (notifyFailed(run)) {
|
|
539
|
+
lines.push(`notify: not delivered — ${run.notify.reason}`)
|
|
540
|
+
}
|
|
541
|
+
if (run.cancelPending) {
|
|
542
|
+
lines.push('cancel: requested, but the process running this run has not confirmed yet; check superagent_status again in a few seconds')
|
|
543
|
+
}
|
|
544
|
+
for (const subtask of run.subtasks) {
|
|
545
|
+
const tokens = subtask.usage
|
|
546
|
+
? ` ${subtask.usage.inputTokens} in / ${subtask.usage.outputTokens} out${subtaskCostText(subtask)}`
|
|
547
|
+
: ''
|
|
548
|
+
// A subtask waiting on a dependency is not running and not failed; saying
|
|
549
|
+
// which tasks it waits for is the difference between "stuck" and "queued".
|
|
550
|
+
const waiting = subtask.status === 'waiting' && subtask.waitingOn?.length > 0
|
|
551
|
+
? ` — waiting on ${subtask.waitingOn.join(', ')}`
|
|
552
|
+
: ''
|
|
553
|
+
const skipped = subtask.status === 'skipped' && subtask.skippedReason
|
|
554
|
+
? ` — skipped: ${subtask.skippedReason}`
|
|
555
|
+
: ''
|
|
556
|
+
const detail = skipped || (subtask.error ? ` — ${summarizeError(subtask.error)}` : '')
|
|
557
|
+
// A cancelled run never judged its unfinished subtasks, so calling them
|
|
558
|
+
// "pending" or "failed (attempts 0)" would misreport what happened.
|
|
559
|
+
const status = run.status === 'cancelled' && subtask.status !== 'completed'
|
|
560
|
+
? (subtask.attempts > 0 ? 'cancelled' : 'skipped')
|
|
561
|
+
: subtask.status
|
|
562
|
+
lines.push(` [${subtask.index}] ${status} (attempts ${subtask.attempts}) ${subtask.title}${tokens}${waiting}${detail}`)
|
|
563
|
+
}
|
|
564
|
+
const failed = run.subtasks.find(subtask => subtask.error)
|
|
565
|
+
if (failed) {
|
|
566
|
+
const hint = classifyError(failed.error).hint
|
|
567
|
+
if (classifyError(failed.error).id !== 'unclassified') lines.push('', `hint: ${hint}`)
|
|
568
|
+
}
|
|
569
|
+
if (includeReport && run.report) {
|
|
570
|
+
lines.push('', 'report:', '', preview(run.report))
|
|
571
|
+
}
|
|
572
|
+
const openQuestion = (run.attention?.items ?? []).find(item => !item.answer)
|
|
573
|
+
if (openQuestion) {
|
|
574
|
+
// The user can act on this line directly; the id is what makes the answer
|
|
575
|
+
// land on the question it belongs to.
|
|
576
|
+
lines.push('', `next: superagent_answer run_id="${run.id}" attention_id="${openQuestion.id ?? 'q1'}" answer="..."`)
|
|
577
|
+
}
|
|
578
|
+
if (!TERMINAL_STATUSES.has(run.status)) {
|
|
579
|
+
lines.push('', `next: superagent_status run_id="${run.id}" wait_seconds=120`)
|
|
580
|
+
} else if (run.status === 'interrupted') {
|
|
581
|
+
lines.push('', `next: superagent_resume run_id="${run.id}"`)
|
|
582
|
+
}
|
|
583
|
+
return lines.join('\n')
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
function formatBytes(bytes) {
|
|
587
|
+
if (bytes < 1024) return `${bytes} B`
|
|
588
|
+
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
|
|
589
|
+
return `${(bytes / 1024 / 1024).toFixed(1)} MB`
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/**
|
|
593
|
+
* The reply for one live injection.
|
|
594
|
+
*
|
|
595
|
+
* The wording separates four states instead of collapsing them into "sent":
|
|
596
|
+
* accepted (the child's inbox holds the message), applied (a step boundary
|
|
597
|
+
* claimed it, with the measured delay), pending (still waiting for that
|
|
598
|
+
* boundary), and missed (the child left before it could read the message).
|
|
599
|
+
*
|
|
600
|
+
* @param {object} run - live run record.
|
|
601
|
+
* @param {object} entry - injection receipt.
|
|
602
|
+
* @param {object | null} degraded - queued-as-followup fallback, when the host has no live channel.
|
|
603
|
+
* @param {{ pollMs: number }} options - poll resolution used for the measurement.
|
|
604
|
+
* @returns {string} the tool reply.
|
|
605
|
+
*/
|
|
606
|
+
function formatInjectionReply(run, entry, degraded, { pollMs }) {
|
|
607
|
+
const targets = entry?.targets ?? []
|
|
608
|
+
const accepted = targets.filter(target => target.messageId)
|
|
609
|
+
const applied = targets.filter(target => target.status === 'applied')
|
|
610
|
+
const missed = targets.filter(target => target.status === 'missed')
|
|
611
|
+
const failed = targets.filter(target => target.status === 'failed')
|
|
612
|
+
const pending = targets.filter(target => target.status === 'pending')
|
|
613
|
+
const lines = []
|
|
614
|
+
|
|
615
|
+
if (degraded) {
|
|
616
|
+
lines.push(
|
|
617
|
+
`instruction ${entry.id} could not be delivered live on run ${run.id}: ${degraded.reason}`,
|
|
618
|
+
`it was queued as instruction ${degraded.followup.id} instead, and takes effect at ${degraded.effect.detail} `
|
|
619
|
+
+ `(boundary: ${degraded.effect.boundary}).`,
|
|
620
|
+
'a worker that is already running is not interrupted and does not see it.',
|
|
621
|
+
)
|
|
622
|
+
return lines.join('\n')
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
lines.push(
|
|
626
|
+
`instruction ${entry.id} accepted by ${accepted.length}/${targets.length} running worker(s) on run ${run.id} — `
|
|
627
|
+
+ `${run.status}`,
|
|
628
|
+
)
|
|
629
|
+
for (const target of targets) {
|
|
630
|
+
const who = `subtask ${target.subtaskIndex} (child ${target.childId})`
|
|
631
|
+
if (target.status === 'applied') {
|
|
632
|
+
lines.push(` ${who}: seen at the child's next step after ${target.latencyMs ?? '?'} ms${target.via ? ` via ${target.via}` : ''}`)
|
|
633
|
+
} else if (target.status === 'pending') {
|
|
634
|
+
lines.push(` ${who}: accepted (message ${target.messageId}); it has not reached a step boundary yet`)
|
|
635
|
+
} else if (target.status === 'missed') {
|
|
636
|
+
lines.push(` ${who}: missed — ${target.missedReason}`)
|
|
637
|
+
} else {
|
|
638
|
+
lines.push(` ${who}: not delivered — ${target.error ?? 'unknown error'}`)
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
const stats = run.injectionStats
|
|
642
|
+
const worst = Number.isFinite(stats?.worstLatencyMs) ? `${stats.worstLatencyMs} ms` : 'not measured yet'
|
|
643
|
+
lines.push(
|
|
644
|
+
'delivery: steering is read at the child\'s next step boundary, just before its next model request. It does not '
|
|
645
|
+
+ 'interrupt a model call already in flight, so the worst case is the remainder of that step (its model response '
|
|
646
|
+
+ 'plus tool batch).',
|
|
647
|
+
`measured on this run: worst ${worst} over ${stats?.samples ?? 0} claimed message(s); the poll resolution is `
|
|
648
|
+
+ `${pollMs} ms.`,
|
|
649
|
+
)
|
|
650
|
+
if (pending.length > 0) {
|
|
651
|
+
lines.push(
|
|
652
|
+
`not seen yet: ${pending.length} message(s) are still waiting at a live child's boundary; this reply does not `
|
|
653
|
+
+ 'claim they were read. superagent_status shows the receipt once the boundary claims it.',
|
|
654
|
+
)
|
|
655
|
+
}
|
|
656
|
+
if (missed.length + failed.length > 0) {
|
|
657
|
+
lines.push(
|
|
658
|
+
`${missed.length + failed.length} message(s) never entered a prompt. If the work must still change, send the `
|
|
659
|
+
+ 'instruction again to a running worker, or use superagent_followup for the next prompt.',
|
|
660
|
+
)
|
|
661
|
+
}
|
|
662
|
+
lines.push('', formatRun(run, { includeReport: false }))
|
|
663
|
+
return lines.join('\n')
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
/** True when a run finished but its owner was never told, and that is a problem. */
|
|
667
|
+
function notifyFailed(run) {
|
|
668
|
+
if (!run.notify || run.notify.delivered) return false
|
|
669
|
+
return !/^(skipped|disabled):/.test(String(run.notify.reason ?? ''))
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
/** What a failed run already tried, so the message is not just "it broke". */
|
|
673
|
+
function triedLine(run) {
|
|
674
|
+
const attempts = run.limits?.attempts ?? 1
|
|
675
|
+
const parts = [`tried: ${attempts} attempt(s) per subtask`]
|
|
676
|
+
if (run.selfHeal?.rounds > 0) {
|
|
677
|
+
parts.push(`${run.selfHeal.rounds} self-heal round(s), ${run.selfHeal.recovered ?? 0} recovered`)
|
|
678
|
+
}
|
|
679
|
+
if (run.selfHeal?.model) parts.push(`switched to ${run.selfHeal.model} for the retry`)
|
|
680
|
+
return `${parts.join('; ')}.`
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
function formatList(runs, limit, stats = null) {
|
|
684
|
+
if (runs.length === 0) return 'no superagent runs recorded'
|
|
685
|
+
const rows = runs.slice(0, limit).map(run => {
|
|
686
|
+
const completed = run.subtasks.filter(subtask => subtask.status === 'completed').length
|
|
687
|
+
return `${run.id} ${run.status.padEnd(11)} ${completed}/${run.subtasks.length} done `
|
|
688
|
+
+ `${run.goal.slice(0, 70)}${notifyFailed(run) ? ' (result not delivered to the session)' : ''}`
|
|
689
|
+
})
|
|
690
|
+
const lines = [`${runs.length} run(s):`, ...rows]
|
|
691
|
+
if (stats) {
|
|
692
|
+
lines.push('', `state: ${stats.files} file(s), ${formatBytes(stats.bytes)} in ${stats.root}`
|
|
693
|
+
+ (stats.corrupt ? ` (${stats.corrupt} quarantined file(s))` : ''))
|
|
694
|
+
if (stats.memory) {
|
|
695
|
+
lines.push(`memory: ${stats.memory.entries} note(s), ${formatBytes(stats.memory.bytes)} in ${path.dirname(stats.memory.path)}`)
|
|
696
|
+
}
|
|
697
|
+
if (stats.pendingNotifications > 0) {
|
|
698
|
+
lines.push(`notifications: ${stats.pendingNotifications} run(s) held back by the hourly limit; `
|
|
699
|
+
+ 'they are folded into the next message')
|
|
700
|
+
}
|
|
701
|
+
if (stats.ledger) {
|
|
702
|
+
const ledger = stats.ledger
|
|
703
|
+
if (ledger.runs === 0) {
|
|
704
|
+
lines.push(`ledger: no spend recorded in the last ${stats.ledgerDays} days`)
|
|
705
|
+
} else if (ledger.priced === 0) {
|
|
706
|
+
lines.push(`ledger: ${ledger.runs} run(s) in the last ${stats.ledgerDays} days are unpriced — `
|
|
707
|
+
+ 'no configured price matches their models, so no total is claimed')
|
|
708
|
+
} else {
|
|
709
|
+
const total = ledger.mixedCurrency
|
|
710
|
+
? `${formatMoney({ totalMicros: ledger.totalMicros, currency: ledger.currency ?? 'USD' })}`
|
|
711
|
+
: formatMoney({ totalMicros: ledger.totalMicros, currency: ledger.currency })
|
|
712
|
+
lines.push(`ledger: ${total} across ${ledger.priced} priced run(s) in the last ${stats.ledgerDays} days`
|
|
713
|
+
+ (ledger.unpricedRuns > 0 ? ` (${ledger.unpricedRuns} run(s) partially unpriced)` : '')
|
|
714
|
+
+ (ledger.mixedCurrency ? ' (mixed currencies; figure uses the first)' : ''))
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
return lines.join('\n')
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
function toolText(text) {
|
|
722
|
+
return [{ type: 'text', text }]
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
/**
|
|
726
|
+
* Render one audit query as a short report: the window, how the events break
|
|
727
|
+
* down, and the latest rows. The full detail stays one export away, so this
|
|
728
|
+
* never floods the session with a thousand lines it cannot use.
|
|
729
|
+
*/
|
|
730
|
+
function formatAudit(result, { limit = 8 } = {}) {
|
|
731
|
+
const { events, scanned, invalid, torn, file } = result
|
|
732
|
+
const notes = []
|
|
733
|
+
if (invalid) notes.push(`${invalid} unreadable line(s) skipped`)
|
|
734
|
+
if (torn) notes.push('1 torn trailing line ignored')
|
|
735
|
+
const tail = notes.length > 0 ? `; ${notes.join('; ')}` : ''
|
|
736
|
+
if (events.length === 0) return `audit: no matching events (${scanned} scanned in ${file}${tail})`
|
|
737
|
+
const tally = field => {
|
|
738
|
+
const counts = new Map()
|
|
739
|
+
for (const event of events) {
|
|
740
|
+
const key = event[field] ?? 'none'
|
|
741
|
+
counts.set(key, (counts.get(key) ?? 0) + 1)
|
|
742
|
+
}
|
|
743
|
+
return [...counts.entries()]
|
|
744
|
+
.sort((a, b) => b[1] - a[1])
|
|
745
|
+
.map(([key, count]) => `${key} ${count}`)
|
|
746
|
+
.join(', ')
|
|
747
|
+
}
|
|
748
|
+
const lines = [
|
|
749
|
+
`audit: ${events.length} event(s) match (${scanned} scanned in ${file}${tail})`,
|
|
750
|
+
`window: ${events[0].at} .. ${events.at(-1).at}`,
|
|
751
|
+
`decision: ${tally('decision')}`,
|
|
752
|
+
`kind: ${tally('kind')}`,
|
|
753
|
+
`result: ${tally('result')}`,
|
|
754
|
+
'latest:',
|
|
755
|
+
]
|
|
756
|
+
for (const event of events.slice(-Math.max(1, limit))) {
|
|
757
|
+
lines.push(
|
|
758
|
+
` ${event.at} ${String(event.decision ?? '-').padEnd(7)} ${String(event.kind).padEnd(12)} `
|
|
759
|
+
+ `${String(event.runId ?? '-').padEnd(14)} ${event.rule ?? '-'} ${event.target ?? ''}`.trimEnd(),
|
|
760
|
+
)
|
|
761
|
+
}
|
|
762
|
+
return lines.join('\n')
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
function defineTool(spec) {
|
|
766
|
+
return {
|
|
767
|
+
name: spec.name,
|
|
768
|
+
description: spec.description,
|
|
769
|
+
parameters: { type: 'object', properties: spec.properties, ...(spec.required?.length ? { required: spec.required } : {}) },
|
|
770
|
+
output: { schema: { type: 'string' }, render: (_args, value) => toolText(value) },
|
|
771
|
+
execute: spec.execute,
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
/**
|
|
776
|
+
* Mount the plugin.
|
|
777
|
+
* @param {object} ctx - Cordis context.
|
|
778
|
+
* @param {object} [config] - row config from `cordis.patch.yml`.
|
|
779
|
+
*/
|
|
780
|
+
export function apply(ctx, config) {
|
|
781
|
+
const log = message => console.error(`[dsh-superagent] ${message}`)
|
|
782
|
+
const configuredPort = config?.controlPort
|
|
783
|
+
const configuredWorkbenchPort = config?.workbenchPort
|
|
784
|
+
const cfg = resolveConfig(config)
|
|
785
|
+
if (configuredPort !== undefined && configuredPort !== null && cfg.controlPort === null) {
|
|
786
|
+
log(`controlPort ${JSON.stringify(configuredPort)} is not a whole number in 0–65535; the local HTTP control plane stays off`)
|
|
787
|
+
}
|
|
788
|
+
if (configuredWorkbenchPort !== undefined && configuredWorkbenchPort !== null && cfg.workbenchPort === null) {
|
|
789
|
+
log(`workbenchPort ${JSON.stringify(configuredWorkbenchPort)} is not a whole number in 0–65535; the workspace panel stays off`)
|
|
790
|
+
}
|
|
791
|
+
if (!ctx?.tools || typeof ctx.tools.register !== 'function') {
|
|
792
|
+
console.error('[dsh-superagent] host exposes no tools service; plugin disabled')
|
|
793
|
+
return
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
const baseStore = createStore(resolveStateRoot(cfg.stateDir), { warn: log })
|
|
797
|
+
const workbenchRoot = cfg.workbenchRoot ? path.resolve(cfg.workbenchRoot) : process.cwd()
|
|
798
|
+
// The panel reads `run.changes` from the durable record. The tracker writes
|
|
799
|
+
// that field through the same store the orchestrator already uses, so the
|
|
800
|
+
// orchestrator itself needs no edit and the panel can stay opt-in.
|
|
801
|
+
const changeTracker = cfg.workbenchPort === null
|
|
802
|
+
? null
|
|
803
|
+
: createRunChangeTracker({ store: baseStore, root: workbenchRoot, stateRoot: baseStore.root, warn: log })
|
|
804
|
+
const store = changeTracker?.store ?? baseStore
|
|
805
|
+
const home = process.env.DSH_HOME?.trim() || path.join(os.homedir(), '.dsh')
|
|
806
|
+
const readUsage = createUsageReader({ sessionsRoot: path.join(home, 'sessions'), warn: log })
|
|
807
|
+
// The ledger is an append-only history of priced runs. Writing it here, from
|
|
808
|
+
// the read paths, keeps it out of the scheduling loop: a status or list call
|
|
809
|
+
// is already a snapshot of finished work, and a run is recorded exactly once.
|
|
810
|
+
const ledger = createLedger(store.root, { warn: log })
|
|
811
|
+
const LEDGER_WINDOW_DAYS = 30
|
|
812
|
+
|
|
813
|
+
/** Append finished runs to the spend ledger; a ledger fault never blocks a tool. */
|
|
814
|
+
async function recordSpend(runs) {
|
|
815
|
+
for (const run of runs) {
|
|
816
|
+
try {
|
|
817
|
+
await ledger.record(run)
|
|
818
|
+
} catch (error) {
|
|
819
|
+
log(`ledger: cannot record run ${run?.id}: ${error?.message ?? error}`)
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
// A state directory inside the installed package would put the notebook in a
|
|
825
|
+
// directory that is meant to be shipped byte-for-byte from git. Refuse rather
|
|
826
|
+
// than rely on the `.gitignore` the notebook writes for itself.
|
|
827
|
+
const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
|
828
|
+
const memoryBlocked = isInside(store.root, packageRoot)
|
|
829
|
+
const memory = cfg.memory && !memoryBlocked ? createMemory(store.root, { warn: log }) : null
|
|
830
|
+
if (cfg.memory && memoryBlocked) {
|
|
831
|
+
log(`cross-run memory stays off: stateDir ${store.root} is inside the installed package; point stateDir elsewhere`)
|
|
832
|
+
}
|
|
833
|
+
// Built-ins need no storage; only custom templates touch the state directory,
|
|
834
|
+
// and a state directory inside the package must not receive new files.
|
|
835
|
+
const templates = createTemplateStore(store.root, { warn: log })
|
|
836
|
+
// The trail and its policy live beside the run state, so one directory holds
|
|
837
|
+
// everything a reviewer needs. A policy the user did not name is picked up
|
|
838
|
+
// only when it already exists; without one, runs behave exactly as before.
|
|
839
|
+
const auditDir = cfg.auditDir ? path.resolve(cfg.auditDir) : path.join(store.root, 'audit')
|
|
840
|
+
const implicitPolicy = path.join(store.root, 'policy.json')
|
|
841
|
+
const policyFile = cfg.policyFile
|
|
842
|
+
? path.resolve(cfg.policyFile)
|
|
843
|
+
: (existsSync(implicitPolicy) ? implicitPolicy : null)
|
|
844
|
+
const auditBlocked = isInside(auditDir, packageRoot)
|
|
845
|
+
const auditor = cfg.audit && !auditBlocked ? createAuditor({ dir: auditDir, policyFile, warn: log }) : null
|
|
846
|
+
if (cfg.audit && auditBlocked) {
|
|
847
|
+
log(`audit trail stays off: ${auditDir} is inside the installed package; point stateDir or auditDir elsewhere`)
|
|
848
|
+
}
|
|
849
|
+
if (auditor) {
|
|
850
|
+
auditor.policyError()
|
|
851
|
+
.then(error => {
|
|
852
|
+
if (error) log(error.message ?? String(error))
|
|
853
|
+
})
|
|
854
|
+
.catch(() => {})
|
|
855
|
+
log(`audit trail ${auditor.file}; policy ${policyFile ?? 'none (permissive)'}`)
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
// The guard is mounted on the host's tool pipeline, scoped to children this
|
|
859
|
+
// plugin spawns. `process.cwd()` is only a fallback: every call uses the
|
|
860
|
+
// child session's own workspace when the host exposes one.
|
|
861
|
+
const guard = createGuard({ config: cfg.guard, cwd: process.cwd(), warn: log })
|
|
862
|
+
if (guard.enabled) {
|
|
863
|
+
const enforce = exec => {
|
|
864
|
+
const verdict = guard.checkToolCall(exec)
|
|
865
|
+
if (!verdict.blocked) return undefined
|
|
866
|
+
log(`guard blocked ${exec?.name ?? 'tool'} for ${verdict.label ?? 'a worker'}: ${verdict.rule} — ${verdict.reason}`)
|
|
867
|
+
// A block is evidence, so it belongs in the same trail as every other
|
|
868
|
+
// decision. The guard owns the verdict; the trail only records it.
|
|
869
|
+
if (auditor && typeof auditor.record === 'function') {
|
|
870
|
+
auditor.record({
|
|
871
|
+
kind: 'blocked',
|
|
872
|
+
action: exec?.name ?? 'tool',
|
|
873
|
+
target: verdict.detail ?? null,
|
|
874
|
+
actor: verdict.label ?? null,
|
|
875
|
+
decision: 'deny',
|
|
876
|
+
result: 'blocked',
|
|
877
|
+
rule: verdict.rule ?? null,
|
|
878
|
+
source: 'guard',
|
|
879
|
+
meta: { reason: verdict.reason ?? null },
|
|
880
|
+
}).catch(error => log(`audit: cannot record guard block: ${error?.message ?? error}`))
|
|
881
|
+
}
|
|
882
|
+
return verdict.reasonText
|
|
883
|
+
}
|
|
884
|
+
let hooked = false
|
|
885
|
+
if (typeof ctx.tools.guard === 'function') {
|
|
886
|
+
const release = ctx.tools.guard(enforce)
|
|
887
|
+
hooked = true
|
|
888
|
+
if (typeof release === 'function' && typeof ctx.effect === 'function') {
|
|
889
|
+
ctx.effect(() => () => release())
|
|
890
|
+
}
|
|
891
|
+
} else if (typeof ctx.on === 'function') {
|
|
892
|
+
ctx.on('tools/pre-execute', async (exec, next) => {
|
|
893
|
+
const reason = enforce(exec)
|
|
894
|
+
return reason ? { kind: 'deny', reason } : next()
|
|
895
|
+
})
|
|
896
|
+
hooked = true
|
|
897
|
+
}
|
|
898
|
+
if (!hooked) {
|
|
899
|
+
log('guard is enabled but this host exposes neither tools.guard nor tools/pre-execute; child calls are not gated')
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
const notifyPolicy = createNotifyPolicy({
|
|
904
|
+
stateFile: path.join(store.root, 'notifications.json'),
|
|
905
|
+
maxPerHour: cfg.maxNotificationsPerHour,
|
|
906
|
+
warn: log,
|
|
907
|
+
})
|
|
908
|
+
// One wake-up per run, delivered in order per session. A busy session loop
|
|
909
|
+
// can reject a followup, so the same message is retried with backoff instead
|
|
910
|
+
// of being reported as lost on the first refusal.
|
|
911
|
+
const outbox = createOutbox({ retries: cfg.notifyRetries, delayMs: cfg.notifyRetryDelayMs })
|
|
912
|
+
|
|
913
|
+
/** Child sessions spawned by this process; a run may not be started from one. */
|
|
914
|
+
const childIds = new Set()
|
|
915
|
+
|
|
916
|
+
/**
|
|
917
|
+
* The subagent service is optional, so it is read from the service store at
|
|
918
|
+
* call time rather than declared as an injection: a profile without it must
|
|
919
|
+
* still mount the eleven tools (they then explain what is missing), and reading
|
|
920
|
+
* it lazily also sees a service that registers after this plugin.
|
|
921
|
+
*/
|
|
922
|
+
function getSubagents() {
|
|
923
|
+
if (typeof ctx.get === 'function') {
|
|
924
|
+
const service = ctx.get('subagents')
|
|
925
|
+
if (service) return service
|
|
926
|
+
}
|
|
927
|
+
// The direct property is topology-sensitive on a real host; it is only a
|
|
928
|
+
// fallback for test contexts that provide the service without a registry.
|
|
929
|
+
try {
|
|
930
|
+
return ctx.subagents
|
|
931
|
+
} catch {
|
|
932
|
+
return undefined
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
/** The agent registry, read lazily for the same reason as `subagents`. */
|
|
937
|
+
function getAgents() {
|
|
938
|
+
if (typeof ctx.get === 'function') {
|
|
939
|
+
const service = ctx.get('agents')
|
|
940
|
+
if (service) return service
|
|
941
|
+
}
|
|
942
|
+
return undefined
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
/** Remember a child id for the recursion guard without growing forever. */
|
|
946
|
+
function rememberChild(childId) {
|
|
947
|
+
if (!childId) return
|
|
948
|
+
childIds.add(childId)
|
|
949
|
+
if (childIds.size > 512) childIds.delete(childIds.values().next().value)
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
/**
|
|
953
|
+
* Map a run outcome to one message for the owning session.
|
|
954
|
+
*
|
|
955
|
+
* The notification policy decides first: a cancelled run is never announced,
|
|
956
|
+
* and a burst above the hourly cap is buffered instead of waking the session
|
|
957
|
+
* once per run. The followup is awaited: an unhandled rejection from it would
|
|
958
|
+
* otherwise escape as a host-level error while the run already claims it was
|
|
959
|
+
* delivered.
|
|
960
|
+
*/
|
|
961
|
+
async function notifyParent(run) {
|
|
962
|
+
if (run.notified) return { delivered: false, reason: 'skipped: the owning session was already notified' }
|
|
963
|
+
if (!cfg.notifyOnComplete) return { delivered: false, reason: 'disabled: notifyOnComplete is false' }
|
|
964
|
+
const agents = typeof ctx.get === 'function' ? ctx.get('agents') : undefined
|
|
965
|
+
const agent = agents && typeof agents.get === 'function' ? agents.get(run.parentSessionId) : undefined
|
|
966
|
+
if (!agent || typeof agent.followup !== 'function') {
|
|
967
|
+
log(`run ${run.id} finished but its session ${run.parentSessionId} is no longer live`)
|
|
968
|
+
return {
|
|
969
|
+
delivered: false,
|
|
970
|
+
reason: `the owning session ${run.parentSessionId} is no longer live; read the report with superagent_status`,
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
// Reserve only once the session is known to exist: a missing session is not
|
|
974
|
+
// an interruption and must not consume the hourly budget.
|
|
975
|
+
const verdict = await notifyPolicy.reserve(run)
|
|
976
|
+
if (!verdict.allowed) return { delivered: false, reason: verdict.reason }
|
|
977
|
+
|
|
978
|
+
const completed = run.subtasks.filter(subtask => subtask.status === 'completed').length
|
|
979
|
+
const decision = (run.attention?.items ?? []).find(item => !item.answer) ?? null
|
|
980
|
+
const questionId = decision?.id ?? (decision ? 'q1' : null)
|
|
981
|
+
const lines = decision
|
|
982
|
+
? [`[superagent] needs your decision on run ${run.id} (question ${questionId}): ${decision.question}`]
|
|
983
|
+
: [`[superagent] run ${run.id} finished: ${run.status} (${completed}/${run.subtasks.length} subtasks).`]
|
|
984
|
+
if (decision) {
|
|
985
|
+
if (decision.options?.length) lines.push(`Options: ${decision.options.join(' / ')}.`)
|
|
986
|
+
lines.push(`The run itself ended as ${run.status} (${completed}/${run.subtasks.length} subtasks).`)
|
|
987
|
+
lines.push(`Answer with superagent_answer attention_id="${questionId}".`)
|
|
988
|
+
} else if (run.attention?.issue) {
|
|
989
|
+
// A malformed block asked for a decision too; keeping it quiet would look
|
|
990
|
+
// like an ordinary finished run.
|
|
991
|
+
lines.push(`Attention: ${run.attention.issue}.`)
|
|
992
|
+
}
|
|
993
|
+
if (!decision && run.status !== 'completed') lines.push(triedLine(run))
|
|
994
|
+
if (run.workspace?.conflicts > 0) {
|
|
995
|
+
// A conflict is the one outcome the user must act on even when the run
|
|
996
|
+
// "completed": saying only "finished: completed" would bury it.
|
|
997
|
+
lines.push(
|
|
998
|
+
`${run.workspace.conflicts} worker branch(es) could not be merged into ${run.workspace.base}; `
|
|
999
|
+
+ 'both sides were kept, so nothing was lost — superagent_status lists the conflicting files and the branch '
|
|
1000
|
+
+ 'to merge by hand.',
|
|
1001
|
+
)
|
|
1002
|
+
} else if (run.workspace?.mode === 'unavailable') {
|
|
1003
|
+
lines.push(`Workspace isolation was unavailable (${run.workspace.reason}), so the workers shared one directory.`)
|
|
1004
|
+
}
|
|
1005
|
+
if (verdict.batch.length > 0) {
|
|
1006
|
+
lines.push(
|
|
1007
|
+
'Also finished since the last update: '
|
|
1008
|
+
+ `${verdict.batch.map(item => `${item.id} ${item.status}`).join('; ')}.`,
|
|
1009
|
+
)
|
|
1010
|
+
}
|
|
1011
|
+
lines.push(`Call superagent_status with run_id="${run.id}" to read the report.`)
|
|
1012
|
+
try {
|
|
1013
|
+
await outbox.enqueue(run.parentSessionId, () => agent.followup({
|
|
1014
|
+
id: randomUUID(),
|
|
1015
|
+
role: 'user',
|
|
1016
|
+
content: [{ type: 'text', text: lines.join(' ') }],
|
|
1017
|
+
source: { kind: 'user' },
|
|
1018
|
+
}))
|
|
1019
|
+
run.notified = true
|
|
1020
|
+
return { delivered: true }
|
|
1021
|
+
} catch (error) {
|
|
1022
|
+
log(`cannot notify session ${run.parentSessionId}: ${error?.message ?? error}`)
|
|
1023
|
+
// The folded runs were reserved but never delivered. Put them back so the
|
|
1024
|
+
// next allowed message still carries them, up to the policy's retry cap.
|
|
1025
|
+
await notifyPolicy.restore(verdict.batch).catch(restoreError => {
|
|
1026
|
+
log(`cannot restore ${verdict.batch.length} batched notification(s): ${restoreError?.message ?? restoreError}`)
|
|
1027
|
+
})
|
|
1028
|
+
return { delivered: false, reason: `waking the session failed: ${error?.message ?? error}` }
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
const orchestrator = createOrchestrator({
|
|
1033
|
+
store,
|
|
1034
|
+
config: cfg,
|
|
1035
|
+
log,
|
|
1036
|
+
readUsage,
|
|
1037
|
+
memory,
|
|
1038
|
+
guard,
|
|
1039
|
+
audit: auditor,
|
|
1040
|
+
notify: notifyParent,
|
|
1041
|
+
// Live delivery into a running child. The steerer reads both services at
|
|
1042
|
+
// call time; the inspector gives the orchestrator the child's inbox state
|
|
1043
|
+
// at the moment its attempt ends, before disposal.
|
|
1044
|
+
steerChild: createChildSteerer({ getSubagents, getAgents, log }),
|
|
1045
|
+
inspectChild(childId) {
|
|
1046
|
+
const agent = getAgents()?.get?.(childId)
|
|
1047
|
+
return { live: Boolean(agent), pending: pendingIds(agent) }
|
|
1048
|
+
},
|
|
1049
|
+
watchChild: createChildWatcher({
|
|
1050
|
+
resolveChild: childId => getAgents()?.get?.(childId),
|
|
1051
|
+
intervalMs: cfg.injectPollMs,
|
|
1052
|
+
}),
|
|
1053
|
+
async spawnChild({ label, prompt, parent, signal, model, runId }) {
|
|
1054
|
+
const subagents = getSubagents()
|
|
1055
|
+
if (!subagents || typeof subagents.startActivation !== 'function') {
|
|
1056
|
+
const error = new Error('subagent service is unavailable; dsh-superagent needs the host subagents service')
|
|
1057
|
+
// The service can also disappear in the middle of a run, when the host
|
|
1058
|
+
// is shutting down. The orchestrator turns this code into `interrupted`
|
|
1059
|
+
// instead of a failed subtask, so the run stays resumable.
|
|
1060
|
+
error.code = 'subagent-unavailable'
|
|
1061
|
+
throw error
|
|
1062
|
+
}
|
|
1063
|
+
const provider = typeof subagents.getProvider === 'function' ? subagents.getProvider(cfg.provider) : undefined
|
|
1064
|
+
const capabilities = provider?.capabilities ?? null
|
|
1065
|
+
const agentOptions = {}
|
|
1066
|
+
// Only the self-heal round passes a model override; everything else keeps
|
|
1067
|
+
// the configured route.
|
|
1068
|
+
const childModel = model ?? cfg.childModel
|
|
1069
|
+
if (cfg.childProvider) agentOptions.provider = cfg.childProvider
|
|
1070
|
+
if (childModel) agentOptions.model = childModel
|
|
1071
|
+
const request = {
|
|
1072
|
+
parent,
|
|
1073
|
+
prompt: [{ type: 'text', text: prompt }],
|
|
1074
|
+
...(Object.keys(agentOptions).length > 0 ? { agentOptions } : {}),
|
|
1075
|
+
}
|
|
1076
|
+
// A preset is the host's only way to give a child a narrower tool set:
|
|
1077
|
+
// the start request has no tool filter in dsh 0.2.2-rc.1.
|
|
1078
|
+
if (cfg.childPreset) {
|
|
1079
|
+
if (capabilities && !capabilities.agentPreset) {
|
|
1080
|
+
throw new Error(
|
|
1081
|
+
`childPreset "${cfg.childPreset}" cannot be applied: subagent provider "${cfg.provider}" does not support `
|
|
1082
|
+
+ 'independent agent presets, so this child would run with this session\'s tools',
|
|
1083
|
+
)
|
|
1084
|
+
}
|
|
1085
|
+
request.agentPreset = cfg.childPreset
|
|
1086
|
+
}
|
|
1087
|
+
// Recursion is bounded unless the operator explicitly left it to the
|
|
1088
|
+
// backend. Silently dropping the cap would hand 8 parallel workers the
|
|
1089
|
+
// right to spawn their own armies.
|
|
1090
|
+
if (cfg.maxSubagentDepth !== 'provider-managed') {
|
|
1091
|
+
if (capabilities && !capabilities.depthLimit) {
|
|
1092
|
+
throw new Error(
|
|
1093
|
+
`subagent provider "${cfg.provider}" cannot enforce maxSubagentDepth (${cfg.maxSubagentDepth}), so child `
|
|
1094
|
+
+ 'agents could spawn their own children without limit; set maxSubagentDepth: provider-managed to accept '
|
|
1095
|
+
+ 'the backend\'s own cap',
|
|
1096
|
+
)
|
|
1097
|
+
}
|
|
1098
|
+
request.maxDepth = cfg.maxSubagentDepth
|
|
1099
|
+
}
|
|
1100
|
+
const activation = await subagents.startActivation({
|
|
1101
|
+
provider: cfg.provider,
|
|
1102
|
+
label,
|
|
1103
|
+
request,
|
|
1104
|
+
signal,
|
|
1105
|
+
delivery: 'caller',
|
|
1106
|
+
})
|
|
1107
|
+
rememberChild(activation.childId)
|
|
1108
|
+
guard.bindChild(activation.childId, { runId, label })
|
|
1109
|
+
return {
|
|
1110
|
+
childId: activation.childId,
|
|
1111
|
+
result: activation.result,
|
|
1112
|
+
dispose: async () => {
|
|
1113
|
+
guard.unbindChild(activation.childId)
|
|
1114
|
+
try {
|
|
1115
|
+
await activation.dispose()
|
|
1116
|
+
} catch (error) {
|
|
1117
|
+
log(`dispose failed for ${activation.childId}: ${error?.message ?? error}`)
|
|
1118
|
+
}
|
|
1119
|
+
},
|
|
1120
|
+
}
|
|
1121
|
+
},
|
|
1122
|
+
})
|
|
1123
|
+
|
|
1124
|
+
// Recovery runs once at mount; tools wait for it so a run left active by a
|
|
1125
|
+
// dead host reads as interrupted before the first tool call sees it. A
|
|
1126
|
+
// failure to initialize the state directory is kept and reported by every
|
|
1127
|
+
// tool: hiding it behind "no runs recorded" is how a broken stateDir looks
|
|
1128
|
+
// like an empty one.
|
|
1129
|
+
let stateError = null
|
|
1130
|
+
const ready = (async () => {
|
|
1131
|
+
try {
|
|
1132
|
+
await orchestrator.recover()
|
|
1133
|
+
} catch (error) {
|
|
1134
|
+
stateError = error instanceof Error ? error : new Error(String(error))
|
|
1135
|
+
log(`state directory is not usable: ${stateError.message}`)
|
|
1136
|
+
return
|
|
1137
|
+
}
|
|
1138
|
+
// Backfill runs that settled while no tool was watching, so the ledger is
|
|
1139
|
+
// complete after a restart. Recording is idempotent: a normal mount adds
|
|
1140
|
+
// nothing for runs already written.
|
|
1141
|
+
try {
|
|
1142
|
+
await recordSpend(await orchestrator.list())
|
|
1143
|
+
} catch (error) {
|
|
1144
|
+
log(`ledger: cannot backfill from runs: ${error?.message ?? error}`)
|
|
1145
|
+
}
|
|
1146
|
+
// Templates are optional: a failure here must not make every run tool
|
|
1147
|
+
// answer with a state error, and the built-ins still work without a file.
|
|
1148
|
+
if (!memoryBlocked) {
|
|
1149
|
+
try {
|
|
1150
|
+
await templates.init()
|
|
1151
|
+
} catch (error) {
|
|
1152
|
+
log(`cannot create the template directory ${templates.dir}: ${error?.message ?? error}`)
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
if (!(cfg.keepRuns > 0) || typeof store.prune !== 'function') return
|
|
1156
|
+
try {
|
|
1157
|
+
const { removed } = await store.prune({ olderThanDays: cfg.keepRuns })
|
|
1158
|
+
if (removed.length > 0) {
|
|
1159
|
+
log(`pruned ${removed.length} terminal run(s) older than ${cfg.keepRuns} day(s): ${removed.join(', ')}`)
|
|
1160
|
+
}
|
|
1161
|
+
} catch (error) {
|
|
1162
|
+
log(`cannot prune old runs: ${error?.message ?? error}`)
|
|
1163
|
+
}
|
|
1164
|
+
})()
|
|
1165
|
+
|
|
1166
|
+
/** True when the host actually provides a subagent service. */
|
|
1167
|
+
function hasSubagents() {
|
|
1168
|
+
const subagents = getSubagents()
|
|
1169
|
+
return Boolean(subagents && typeof subagents.startActivation === 'function')
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
function requireAgent(exec) {
|
|
1173
|
+
const agent = exec?.agent
|
|
1174
|
+
if (!agent || typeof agent !== 'object' || !agent.id) return { error: describeError('no live agent in this tool call context') }
|
|
1175
|
+
if (childIds.has(agent.id)) {
|
|
1176
|
+
return { error: describeError('refused: a superagent worker may not start, resume, or cancel runs; finish your subtask instead') }
|
|
1177
|
+
}
|
|
1178
|
+
return { agent }
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
/**
|
|
1182
|
+
* Resolve the session named by an HTTP caller. An embedded start is a normal
|
|
1183
|
+
* run: it needs a live agent to own the children, and the same recursion
|
|
1184
|
+
* guard as a tool call. A synthetic parent would spawn children no session
|
|
1185
|
+
* owns, so a missing session is an error, never a fallback.
|
|
1186
|
+
* @param {unknown} sessionId - `session_id` from the request body.
|
|
1187
|
+
* @returns {object} live agent.
|
|
1188
|
+
*/
|
|
1189
|
+
function resolveSession(sessionId) {
|
|
1190
|
+
const id = typeof sessionId === 'string' ? sessionId.trim() : ''
|
|
1191
|
+
if (!id) {
|
|
1192
|
+
throw new Error(
|
|
1193
|
+
'no live agent: session_id is required; an HTTP-started run needs an open session to own its child agents',
|
|
1194
|
+
)
|
|
1195
|
+
}
|
|
1196
|
+
const agents = typeof ctx.get === 'function' ? ctx.get('agents') : undefined
|
|
1197
|
+
const agent = agents && typeof agents.get === 'function' ? agents.get(id) : undefined
|
|
1198
|
+
if (!agent || typeof agent !== 'object' || !agent.id) {
|
|
1199
|
+
throw new Error(
|
|
1200
|
+
`no live agent: session ${id} is not open in this host process; open that session, or start the run from a `
|
|
1201
|
+
+ 'tool call inside it',
|
|
1202
|
+
)
|
|
1203
|
+
}
|
|
1204
|
+
if (childIds.has(agent.id)) {
|
|
1205
|
+
throw new Error('refused: a superagent worker may not start or resume runs; finish your subtask instead')
|
|
1206
|
+
}
|
|
1207
|
+
return agent
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
ctx.tools.register(defineTool({
|
|
1211
|
+
name: 'superagent_start',
|
|
1212
|
+
description:
|
|
1213
|
+
'Start a long-horizon autonomous run: a planner decomposes the goal into subtasks, '
|
|
1214
|
+
+ 'independent subtasks run in parallel child agents while ones with a declared dependency wait for it, '
|
|
1215
|
+
+ 'and their reports are merged into one final report. '
|
|
1216
|
+
+ 'Pass mode "direct" for a single self-contained task instead: one worker does it, there is no planner '
|
|
1217
|
+
+ 'or aggregator, and its reply is the report verbatim — use it for one lookup, one edit, one query, or '
|
|
1218
|
+
+ 'one short piece of writing, not for a goal with parts that can be worked in parallel. '
|
|
1219
|
+
+ 'The call returns immediately with a run id; poll it with superagent_status. Runs are persisted, '
|
|
1220
|
+
+ 'so they survive a host restart and can be resumed or cancelled.',
|
|
1221
|
+
properties: {
|
|
1222
|
+
goal: { type: 'string', description: 'The complete goal for the run. Be specific about the expected outcome.' },
|
|
1223
|
+
mode: {
|
|
1224
|
+
type: 'string',
|
|
1225
|
+
enum: ['planned', 'direct'],
|
|
1226
|
+
description: 'planned (default): planner, parallel workers, merged report. direct: one worker runs the whole '
|
|
1227
|
+
+ 'goal, with no planning or aggregation, and its reply is returned unchanged. Choose direct only when the '
|
|
1228
|
+
+ 'task is one self-contained pass that gains nothing from splitting.',
|
|
1229
|
+
},
|
|
1230
|
+
queue: {
|
|
1231
|
+
type: 'boolean',
|
|
1232
|
+
description: 'When maxActiveRuns is already in use, wait for a free slot instead of failing. The run returns '
|
|
1233
|
+
+ `status "queued" with its position, starts automatically when another run finishes, and gives up after `
|
|
1234
|
+
+ `queueTimeoutMinutes (default ${DEFAULTS.queueTimeoutMinutes}). Off by default; at most maxQueuedRuns `
|
|
1235
|
+
+ `(default ${DEFAULTS.maxQueuedRuns}) may wait.`,
|
|
1236
|
+
},
|
|
1237
|
+
max_subtasks: { type: 'number', description: `Cap on planned subtasks (default ${DEFAULTS.maxSubtasks}, max 16).` },
|
|
1238
|
+
max_parallel: { type: 'number', description: `Subtasks allowed to run at once (default ${DEFAULTS.maxParallel}, max 8).` },
|
|
1239
|
+
deadline_minutes: { type: 'number', description: `Wall-clock budget in minutes (default ${DEFAULTS.deadlineMinutes}).` },
|
|
1240
|
+
allow_duplicate: {
|
|
1241
|
+
type: 'boolean',
|
|
1242
|
+
description: 'Start a second run for the same goal even when an active run already has it. '
|
|
1243
|
+
+ 'By default the active run id is returned instead, so a retry cannot double the spend.',
|
|
1244
|
+
},
|
|
1245
|
+
approve_policy: {
|
|
1246
|
+
type: 'boolean',
|
|
1247
|
+
description: 'Release a start that the permission policy holds for confirmation. The approval is '
|
|
1248
|
+
+ 'recorded in the audit trail. It cannot override a policy that denies the start.',
|
|
1249
|
+
},
|
|
1250
|
+
wait_seconds: { type: 'number', description: 'Block up to this many seconds for a terminal status before returning (0 returns immediately).' },
|
|
1251
|
+
},
|
|
1252
|
+
required: ['goal'],
|
|
1253
|
+
async execute(args = {}, exec) {
|
|
1254
|
+
const check = requireAgent(exec)
|
|
1255
|
+
if (check.error) return check.error
|
|
1256
|
+
try {
|
|
1257
|
+
await ready
|
|
1258
|
+
if (stateError) return describeError(stateError)
|
|
1259
|
+
if (!hasSubagents()) {
|
|
1260
|
+
return describeError(
|
|
1261
|
+
'subagent service is unavailable; dsh-superagent needs the host subagents service to create planner, '
|
|
1262
|
+
+ 'worker, and aggregator agents. Enable it in this profile (the base bundle provides it) and restart.',
|
|
1263
|
+
)
|
|
1264
|
+
}
|
|
1265
|
+
const run = await orchestrator.start({
|
|
1266
|
+
goal: args.goal,
|
|
1267
|
+
parentSessionId: check.agent.id,
|
|
1268
|
+
parent: check.agent,
|
|
1269
|
+
clientTimeZone: exec.clientTimeZone,
|
|
1270
|
+
allowDuplicate: args.allow_duplicate === true,
|
|
1271
|
+
mode: args.mode,
|
|
1272
|
+
queue: args.queue === true,
|
|
1273
|
+
approvePolicy: args.approve_policy === true,
|
|
1274
|
+
overrides: {
|
|
1275
|
+
maxSubtasks: args.max_subtasks,
|
|
1276
|
+
maxParallel: args.max_parallel,
|
|
1277
|
+
deadlineMinutes: args.deadline_minutes,
|
|
1278
|
+
},
|
|
1279
|
+
})
|
|
1280
|
+
const waitSeconds = Number(args.wait_seconds) || 0
|
|
1281
|
+
if (waitSeconds > 0) {
|
|
1282
|
+
const finished = await orchestrator.status(run.id, waitSeconds)
|
|
1283
|
+
await recordSpend([finished])
|
|
1284
|
+
// `status` reads the stored run, which never has the transient join
|
|
1285
|
+
// marker; carry it over so the caller can still see it joined.
|
|
1286
|
+
return formatRun(run.deduped ? { ...finished, deduped: true } : finished)
|
|
1287
|
+
}
|
|
1288
|
+
if (run.queue?.waiting) {
|
|
1289
|
+
return `${formatRun(run, { includeReport: false })}\n\nQueued, not started: the run begins automatically when `
|
|
1290
|
+
+ 'an active run finishes. Poll with superagent_status or cancel it with superagent_cancel.'
|
|
1291
|
+
}
|
|
1292
|
+
return `${formatRun(run, { includeReport: false })}\n\nStarted in the background. Poll with superagent_status; `
|
|
1293
|
+
+ 'the run keeps going after this tool call returns.'
|
|
1294
|
+
} catch (error) {
|
|
1295
|
+
return describeError(error)
|
|
1296
|
+
}
|
|
1297
|
+
},
|
|
1298
|
+
}))
|
|
1299
|
+
|
|
1300
|
+
ctx.tools.register(defineTool({
|
|
1301
|
+
name: 'superagent_status',
|
|
1302
|
+
description:
|
|
1303
|
+
'Read one superagent run: status, subtask outcomes, measured token usage, and the final report. '
|
|
1304
|
+
+ 'With wait_seconds it blocks until the run reaches a terminal state or the wait expires.',
|
|
1305
|
+
properties: {
|
|
1306
|
+
run_id: { type: 'string', description: 'Run id returned by superagent_start.' },
|
|
1307
|
+
wait_seconds: { type: 'number', description: 'Block up to this many seconds for a terminal state (default 0).' },
|
|
1308
|
+
},
|
|
1309
|
+
required: ['run_id'],
|
|
1310
|
+
async execute(args = {}) {
|
|
1311
|
+
try {
|
|
1312
|
+
await ready
|
|
1313
|
+
if (stateError) return describeError(stateError)
|
|
1314
|
+
const run = await orchestrator.status(String(args.run_id ?? '').trim(), Number(args.wait_seconds) || 0)
|
|
1315
|
+
await recordSpend([run])
|
|
1316
|
+
return formatRun(run)
|
|
1317
|
+
} catch (error) {
|
|
1318
|
+
return describeError(error)
|
|
1319
|
+
}
|
|
1320
|
+
},
|
|
1321
|
+
}))
|
|
1322
|
+
|
|
1323
|
+
ctx.tools.register(defineTool({
|
|
1324
|
+
name: 'superagent_list',
|
|
1325
|
+
description: 'List recorded superagent runs, newest first, with status and progress.',
|
|
1326
|
+
properties: {
|
|
1327
|
+
limit: { type: 'number', description: 'Maximum rows to print (default 20).' },
|
|
1328
|
+
},
|
|
1329
|
+
async execute(args = {}) {
|
|
1330
|
+
try {
|
|
1331
|
+
await ready
|
|
1332
|
+
if (stateError) return describeError(stateError)
|
|
1333
|
+
const runs = await orchestrator.list()
|
|
1334
|
+
await recordSpend(runs)
|
|
1335
|
+
const stats = typeof store.stats === 'function' ? await store.stats() : null
|
|
1336
|
+
const memoryStats = memory
|
|
1337
|
+
? await memory.stats({ scope: cfg.memoryScope, maxAgeDays: cfg.memoryMaxAgeDays }).catch(() => null)
|
|
1338
|
+
: null
|
|
1339
|
+
const notifyState = await notifyPolicy.summary().catch(() => null)
|
|
1340
|
+
const ledgerStats = await ledger
|
|
1341
|
+
.summarize({ since: Date.now() - LEDGER_WINDOW_DAYS * 86400000 })
|
|
1342
|
+
.catch(() => null)
|
|
1343
|
+
const extra = stats
|
|
1344
|
+
? {
|
|
1345
|
+
...stats,
|
|
1346
|
+
root: store.root,
|
|
1347
|
+
memory: memoryStats,
|
|
1348
|
+
pendingNotifications: notifyState?.pending?.length ?? 0,
|
|
1349
|
+
ledger: ledgerStats,
|
|
1350
|
+
ledgerDays: LEDGER_WINDOW_DAYS,
|
|
1351
|
+
}
|
|
1352
|
+
: null
|
|
1353
|
+
return formatList(runs, Math.max(1, Math.min(100, Number(args.limit) || 20)), extra)
|
|
1354
|
+
} catch (error) {
|
|
1355
|
+
return describeError(error)
|
|
1356
|
+
}
|
|
1357
|
+
},
|
|
1358
|
+
}))
|
|
1359
|
+
|
|
1360
|
+
ctx.tools.register(defineTool({
|
|
1361
|
+
name: 'superagent_cancel',
|
|
1362
|
+
description:
|
|
1363
|
+
'Cancel a superagent run: stops running subtasks, marks the run cancelled, and keeps the state file '
|
|
1364
|
+
+ 'so the partial work stays inspectable.',
|
|
1365
|
+
properties: {
|
|
1366
|
+
run_id: { type: 'string', description: 'Run id to cancel.' },
|
|
1367
|
+
},
|
|
1368
|
+
required: ['run_id'],
|
|
1369
|
+
async execute(args = {}, exec) {
|
|
1370
|
+
const check = requireAgent(exec)
|
|
1371
|
+
if (check.error) return check.error
|
|
1372
|
+
try {
|
|
1373
|
+
await ready
|
|
1374
|
+
if (stateError) return describeError(stateError)
|
|
1375
|
+
const run = await orchestrator.cancel(String(args.run_id ?? '').trim())
|
|
1376
|
+
await recordSpend([run])
|
|
1377
|
+
const head = run.status === 'cancelled'
|
|
1378
|
+
? `cancelled ${run.id}`
|
|
1379
|
+
: run.cancelPending
|
|
1380
|
+
? `cancel requested for ${run.id}, not confirmed by the owning process yet`
|
|
1381
|
+
: `${run.id} is ${run.status}; nothing to cancel`
|
|
1382
|
+
return `${head}\n\n${formatRun(run, { includeReport: false })}`
|
|
1383
|
+
} catch (error) {
|
|
1384
|
+
return describeError(error)
|
|
1385
|
+
}
|
|
1386
|
+
},
|
|
1387
|
+
}))
|
|
1388
|
+
|
|
1389
|
+
ctx.tools.register(defineTool({
|
|
1390
|
+
name: 'superagent_resume',
|
|
1391
|
+
description:
|
|
1392
|
+
'Resume a run that was interrupted by a host restart, ran out of time, or failed part way. '
|
|
1393
|
+
+ 'Completed subtasks are kept; pending and failed ones run again. A completed run is reopened only when it '
|
|
1394
|
+
+ 'holds an answer that never reached a prompt, so its aggregation can apply the decision.',
|
|
1395
|
+
properties: {
|
|
1396
|
+
run_id: { type: 'string', description: 'Run id to resume.' },
|
|
1397
|
+
wait_seconds: { type: 'number', description: 'Block up to this many seconds for a terminal state (default 0).' },
|
|
1398
|
+
force: {
|
|
1399
|
+
type: 'boolean',
|
|
1400
|
+
description: 'Accepted for backward compatibility and ignored: a resume is never refused by maxActiveRuns.',
|
|
1401
|
+
},
|
|
1402
|
+
approve_policy: {
|
|
1403
|
+
type: 'boolean',
|
|
1404
|
+
description: 'Release a resume that the permission policy holds for confirmation. The approval is '
|
|
1405
|
+
+ 'recorded in the audit trail. It cannot override a policy that denies the resume.',
|
|
1406
|
+
},
|
|
1407
|
+
},
|
|
1408
|
+
required: ['run_id'],
|
|
1409
|
+
async execute(args = {}, exec) {
|
|
1410
|
+
const check = requireAgent(exec)
|
|
1411
|
+
if (check.error) return check.error
|
|
1412
|
+
try {
|
|
1413
|
+
await ready
|
|
1414
|
+
if (stateError) return describeError(stateError)
|
|
1415
|
+
if (!hasSubagents()) {
|
|
1416
|
+
return describeError(
|
|
1417
|
+
'subagent service is unavailable; resuming a run needs the host subagents service to create child agents.',
|
|
1418
|
+
)
|
|
1419
|
+
}
|
|
1420
|
+
const run = await orchestrator.resume(
|
|
1421
|
+
String(args.run_id ?? '').trim(),
|
|
1422
|
+
check.agent,
|
|
1423
|
+
exec.clientTimeZone,
|
|
1424
|
+
{ force: args.force === true, approvePolicy: args.approve_policy === true },
|
|
1425
|
+
)
|
|
1426
|
+
const waitSeconds = Number(args.wait_seconds) || 0
|
|
1427
|
+
const current = waitSeconds > 0 ? await orchestrator.status(run.id, waitSeconds) : run
|
|
1428
|
+
await recordSpend([current])
|
|
1429
|
+
return formatRun(current)
|
|
1430
|
+
} catch (error) {
|
|
1431
|
+
return describeError(error)
|
|
1432
|
+
}
|
|
1433
|
+
},
|
|
1434
|
+
}))
|
|
1435
|
+
|
|
1436
|
+
ctx.tools.register(defineTool({
|
|
1437
|
+
name: 'superagent_followup',
|
|
1438
|
+
description:
|
|
1439
|
+
'Add an instruction to a run that is already executing, instead of starting a second run. This is not a live '
|
|
1440
|
+
+ 'channel to the running children: the host has no way to append a message to a child activation, so the '
|
|
1441
|
+
+ 'instruction is queued on the run and carried by the next prompt built for it — the next worker spawn or the '
|
|
1442
|
+
+ 'aggregation, whichever comes first. Subtasks that are already running or finished keep their results. The '
|
|
1443
|
+
+ 'reply states exactly which boundary it will reach.',
|
|
1444
|
+
properties: {
|
|
1445
|
+
run_id: { type: 'string', description: 'Run id returned by superagent_start.' },
|
|
1446
|
+
message: { type: 'string', description: 'The instruction or constraint to add.' },
|
|
1447
|
+
},
|
|
1448
|
+
required: ['run_id', 'message'],
|
|
1449
|
+
async execute(args = {}, exec) {
|
|
1450
|
+
const check = requireAgent(exec)
|
|
1451
|
+
if (check.error) return check.error
|
|
1452
|
+
try {
|
|
1453
|
+
await ready
|
|
1454
|
+
if (stateError) return describeError(stateError)
|
|
1455
|
+
const result = await orchestrator.followup(
|
|
1456
|
+
String(args.run_id ?? '').trim(),
|
|
1457
|
+
args.message,
|
|
1458
|
+
check.agent,
|
|
1459
|
+
)
|
|
1460
|
+
return [
|
|
1461
|
+
`instruction ${result.followup.id} added to run ${result.run.id} — ${result.run.status}`,
|
|
1462
|
+
`when it takes effect: ${result.effect.detail} (boundary: ${result.effect.boundary}).`,
|
|
1463
|
+
'A child that is already running is not interrupted and does not see it.',
|
|
1464
|
+
'',
|
|
1465
|
+
formatRun(result.run, { includeReport: false }),
|
|
1466
|
+
].join('\n')
|
|
1467
|
+
} catch (error) {
|
|
1468
|
+
return describeError(error)
|
|
1469
|
+
}
|
|
1470
|
+
},
|
|
1471
|
+
}))
|
|
1472
|
+
|
|
1473
|
+
ctx.tools.register(defineTool({
|
|
1474
|
+
name: 'superagent_inject',
|
|
1475
|
+
description:
|
|
1476
|
+
'Deliver an instruction into the workers that are running right now, instead of waiting for the next prompt. '
|
|
1477
|
+
+ 'The host reads steering at a child\'s next step boundary, so the message becomes part of that child\'s next '
|
|
1478
|
+
+ 'model request: it never interrupts a model call already in flight, and it arrives only after the current step '
|
|
1479
|
+
+ '(the model response plus its tool batch) finishes. A live child that had already decided to stop runs one more '
|
|
1480
|
+
+ 'turn to read it. The reply reports the measured delay from acceptance to the child\'s next request; a message '
|
|
1481
|
+
+ 'the child never claimed is reported as missed, never as delivered. Use superagent_followup when no worker is '
|
|
1482
|
+
+ 'running or the instruction can wait for the next prompt.',
|
|
1483
|
+
properties: {
|
|
1484
|
+
run_id: { type: 'string', description: 'Run id returned by superagent_start.' },
|
|
1485
|
+
message: { type: 'string', description: 'The instruction or constraint the running workers should read next.' },
|
|
1486
|
+
subtask_index: {
|
|
1487
|
+
type: 'number',
|
|
1488
|
+
description: 'Narrow delivery to one running worker, using its index from superagent_status. Omit to reach every running worker.',
|
|
1489
|
+
},
|
|
1490
|
+
wait_seconds: {
|
|
1491
|
+
type: 'number',
|
|
1492
|
+
description: 'Block up to this many seconds for the children to claim the message, so the reply can report the measured delay (default 0).',
|
|
1493
|
+
},
|
|
1494
|
+
},
|
|
1495
|
+
required: ['run_id', 'message'],
|
|
1496
|
+
async execute(args = {}, exec) {
|
|
1497
|
+
const check = requireAgent(exec)
|
|
1498
|
+
if (check.error) return check.error
|
|
1499
|
+
try {
|
|
1500
|
+
await ready
|
|
1501
|
+
if (stateError) return describeError(stateError)
|
|
1502
|
+
const result = await orchestrator.inject(
|
|
1503
|
+
String(args.run_id ?? '').trim(),
|
|
1504
|
+
args.message,
|
|
1505
|
+
check.agent,
|
|
1506
|
+
{ subtaskIndex: args.subtask_index },
|
|
1507
|
+
)
|
|
1508
|
+
const entry = await orchestrator.waitForInjection(result.run, result.injection, args.wait_seconds)
|
|
1509
|
+
return formatInjectionReply(result.run, entry, result.degraded, { pollMs: cfg.injectPollMs })
|
|
1510
|
+
} catch (error) {
|
|
1511
|
+
return describeError(error)
|
|
1512
|
+
}
|
|
1513
|
+
},
|
|
1514
|
+
}))
|
|
1515
|
+
|
|
1516
|
+
ctx.tools.register(defineTool({
|
|
1517
|
+
name: 'superagent_answer',
|
|
1518
|
+
description:
|
|
1519
|
+
'Answer a question a run asked — the "needs your decision" item with a qN id — so that run continues with the '
|
|
1520
|
+
+ 'decision instead of a new run being started. An active run applies it at its next boundary; a finished run '
|
|
1521
|
+
+ 'is reopened and only its aggregation runs again, now with the answer. The answer is matched to one specific '
|
|
1522
|
+
+ 'question: an unknown, already answered, or expired question is refused instead of being attached to whatever '
|
|
1523
|
+
+ 'is open.',
|
|
1524
|
+
properties: {
|
|
1525
|
+
run_id: { type: 'string', description: 'Run id returned by superagent_start.' },
|
|
1526
|
+
attention_id: {
|
|
1527
|
+
type: 'string',
|
|
1528
|
+
description: 'Question id from superagent_status, e.g. q1. Required when the run has more than one open question.',
|
|
1529
|
+
},
|
|
1530
|
+
answer: { type: 'string', description: 'The decision itself; one of the listed options is enough, free text is allowed.' },
|
|
1531
|
+
wait_seconds: { type: 'number', description: 'Block up to this many seconds for the run to settle again (default 0).' },
|
|
1532
|
+
},
|
|
1533
|
+
required: ['run_id', 'answer'],
|
|
1534
|
+
async execute(args = {}, exec) {
|
|
1535
|
+
const check = requireAgent(exec)
|
|
1536
|
+
if (check.error) return check.error
|
|
1537
|
+
try {
|
|
1538
|
+
await ready
|
|
1539
|
+
if (stateError) return describeError(stateError)
|
|
1540
|
+
const result = await orchestrator.answer(
|
|
1541
|
+
String(args.run_id ?? '').trim(),
|
|
1542
|
+
args.attention_id,
|
|
1543
|
+
args.answer,
|
|
1544
|
+
check.agent,
|
|
1545
|
+
exec.clientTimeZone,
|
|
1546
|
+
)
|
|
1547
|
+
let head
|
|
1548
|
+
if (result.resumed) {
|
|
1549
|
+
head = `answered ${result.attentionId} on run ${result.run.id}; the run was reopened and is ${result.run.status} `
|
|
1550
|
+
+ `again — it applies the answer at ${result.effect.detail}`
|
|
1551
|
+
} else if (result.reason) {
|
|
1552
|
+
head = `answered ${result.attentionId} on run ${result.run.id}, but the run was not restarted: ${result.reason}. `
|
|
1553
|
+
+ 'The answer is saved; call superagent_resume when you want it applied.'
|
|
1554
|
+
} else {
|
|
1555
|
+
head = `answered ${result.attentionId} on run ${result.run.id}; it takes effect at ${result.effect.detail}`
|
|
1556
|
+
}
|
|
1557
|
+
const waitSeconds = Number(args.wait_seconds) || 0
|
|
1558
|
+
const current = result.resumed && waitSeconds > 0
|
|
1559
|
+
? await orchestrator.status(result.run.id, waitSeconds)
|
|
1560
|
+
: result.run
|
|
1561
|
+
return `${head}.\n\n${formatRun(current)}`
|
|
1562
|
+
} catch (error) {
|
|
1563
|
+
return describeError(error)
|
|
1564
|
+
}
|
|
1565
|
+
},
|
|
1566
|
+
}))
|
|
1567
|
+
|
|
1568
|
+
ctx.tools.register(defineTool({
|
|
1569
|
+
name: 'superagent_memory',
|
|
1570
|
+
description:
|
|
1571
|
+
'Read or correct the cross-run notebook: short notes that earlier runs left for the next one. '
|
|
1572
|
+
+ 'A note is advisory and can be stale; a new note with the same key supersedes it, and forget retracts it.',
|
|
1573
|
+
properties: {
|
|
1574
|
+
action: {
|
|
1575
|
+
type: 'string',
|
|
1576
|
+
enum: ['list', 'search', 'set', 'forget'],
|
|
1577
|
+
description: 'List notes, search them by keyword or tag, set (add or correct) one, or forget one.',
|
|
1578
|
+
},
|
|
1579
|
+
key: { type: 'string', description: 'Short topic key. A new note with the same key replaces the older one.' },
|
|
1580
|
+
kind: { type: 'string', enum: [...MEMORY_KINDS], description: 'decision, pitfall, next, dispatch, or note.' },
|
|
1581
|
+
text: { type: 'string', description: 'The durable fact to record (set only).' },
|
|
1582
|
+
query: {
|
|
1583
|
+
type: 'string',
|
|
1584
|
+
description: 'Keywords to rank notes by (search only). The goal of the current task works well.',
|
|
1585
|
+
},
|
|
1586
|
+
tags: {
|
|
1587
|
+
type: 'array',
|
|
1588
|
+
items: { type: 'string' },
|
|
1589
|
+
description: 'Topic labels to match exactly (search) or to attach to a note (set).',
|
|
1590
|
+
},
|
|
1591
|
+
scope: {
|
|
1592
|
+
type: 'string',
|
|
1593
|
+
description: 'Notebook scope: "rules" for project rules, "profile" for user preferences, '
|
|
1594
|
+
+ 'or the run scope (default) that earlier runs write to.',
|
|
1595
|
+
},
|
|
1596
|
+
limit: { type: 'number', description: 'Maximum notes to print (default 20).' },
|
|
1597
|
+
},
|
|
1598
|
+
required: ['action'],
|
|
1599
|
+
async execute(args = {}, exec) {
|
|
1600
|
+
const check = requireAgent(exec)
|
|
1601
|
+
if (check.error) return check.error
|
|
1602
|
+
if (!memory) {
|
|
1603
|
+
return describeError(
|
|
1604
|
+
'cross-run memory is disabled (memory: false, or stateDir points inside the installed package)',
|
|
1605
|
+
)
|
|
1606
|
+
}
|
|
1607
|
+
try {
|
|
1608
|
+
await ready
|
|
1609
|
+
if (stateError) return describeError(stateError)
|
|
1610
|
+
const action = String(args.action ?? '').trim().toLowerCase()
|
|
1611
|
+
// A run writes to the configured scope; `rules` and `profile` are
|
|
1612
|
+
// curated by hand and read into every run, so the tool can address
|
|
1613
|
+
// them explicitly.
|
|
1614
|
+
const scope = args.scope === undefined || args.scope === null
|
|
1615
|
+
? cfg.memoryScope
|
|
1616
|
+
: normalizeScope(args.scope)
|
|
1617
|
+
if (action === 'list') {
|
|
1618
|
+
// Capped at 30: this output goes straight into the model context, and a
|
|
1619
|
+
// 200-row dump would cost more than the notes are worth.
|
|
1620
|
+
const limit = Math.max(1, Math.min(30, Number(args.limit) || 20))
|
|
1621
|
+
const result = await memory.list({ scope, limit, maxAgeDays: cfg.memoryMaxAgeDays })
|
|
1622
|
+
if (result.total === 0) return `no notes recorded in scope "${scope}" (${result.path})`
|
|
1623
|
+
const rows = result.entries.map(entry => `- ${entry.key} [${entry.kind}] ${entry.text}`)
|
|
1624
|
+
const notes = result.bad ? `\n\n${result.bad} unreadable line(s) skipped` : ''
|
|
1625
|
+
return `${result.total} note(s) in scope "${scope}" (${result.path})\n\n${rows.join('\n')}${notes}`
|
|
1626
|
+
}
|
|
1627
|
+
if (action === 'search') {
|
|
1628
|
+
const query = String(args.query ?? '').trim()
|
|
1629
|
+
const tags = Array.isArray(args.tags) ? args.tags : []
|
|
1630
|
+
if (!query && tags.length === 0) {
|
|
1631
|
+
return describeError('search needs a query, tags, or both; call action="list" to read everything')
|
|
1632
|
+
}
|
|
1633
|
+
const limit = Math.max(1, Math.min(20, Number(args.limit) || 10))
|
|
1634
|
+
const result = await memory.recall({
|
|
1635
|
+
scope,
|
|
1636
|
+
query,
|
|
1637
|
+
tags,
|
|
1638
|
+
maxEntries: limit,
|
|
1639
|
+
maxAgeDays: cfg.memoryMaxAgeDays,
|
|
1640
|
+
})
|
|
1641
|
+
if (result.matched === 0) {
|
|
1642
|
+
return `no note in scope "${scope}" matches ${query ? `“${query}”` : 'those tags'} `
|
|
1643
|
+
+ `(${result.total} note(s) recorded; action="list" shows them all)`
|
|
1644
|
+
}
|
|
1645
|
+
// The score and its parts are printed so a ranking can be argued with
|
|
1646
|
+
// instead of taken on faith.
|
|
1647
|
+
const rows = result.entries.map(entry => {
|
|
1648
|
+
const run = entry.source.runId ?? 'manual'
|
|
1649
|
+
return `- ${entry.key} [${entry.kind}] score ${entry.score.toFixed(2)} `
|
|
1650
|
+
+ `(keyword ${entry.keyword.toFixed(2)}, tag ${entry.tag.toFixed(2)}) `
|
|
1651
|
+
+ `from run ${run}, ${String(entry.source.ts ?? '').slice(0, 10)}: ${entry.text}`
|
|
1652
|
+
})
|
|
1653
|
+
return `${result.matched} of ${result.total} note(s) in scope "${scope}" match, best first\n\n${rows.join('\n')}`
|
|
1654
|
+
}
|
|
1655
|
+
if (action === 'forget') {
|
|
1656
|
+
const key = String(args.key ?? '').trim()
|
|
1657
|
+
if (!key) return describeError('forget needs the key of the note to retract; call action="list" first')
|
|
1658
|
+
const result = await memory.forget({ scope, key })
|
|
1659
|
+
return result.forgotten
|
|
1660
|
+
? `retracted "${key}" in scope "${scope}"; later runs will not see it`
|
|
1661
|
+
: describeError(result.reason ?? 'cannot retract that note')
|
|
1662
|
+
}
|
|
1663
|
+
if (action === 'set') {
|
|
1664
|
+
const key = String(args.key ?? '').trim()
|
|
1665
|
+
const text = String(args.text ?? '').trim()
|
|
1666
|
+
if (!key || !text) return describeError('set needs both key and text')
|
|
1667
|
+
const result = await memory.set({ scope, key, kind: args.kind, text, tags: args.tags })
|
|
1668
|
+
return result.written > 0
|
|
1669
|
+
? `recorded "${key}" in scope "${scope}"; later runs will see it`
|
|
1670
|
+
: describeError(result.reason ?? 'cannot record that note')
|
|
1671
|
+
}
|
|
1672
|
+
return describeError(`unknown action "${args.action}"; use list, search, set, or forget`)
|
|
1673
|
+
} catch (error) {
|
|
1674
|
+
return describeError(error)
|
|
1675
|
+
}
|
|
1676
|
+
},
|
|
1677
|
+
}))
|
|
1678
|
+
|
|
1679
|
+
/**
|
|
1680
|
+
* A template failure already names the concrete problem (which parameters
|
|
1681
|
+
* are missing, which field is not allowed), so it gets its own hint instead
|
|
1682
|
+
* of the generic "this came from the host" text.
|
|
1683
|
+
*/
|
|
1684
|
+
function templateProblem(error) {
|
|
1685
|
+
const hints = {
|
|
1686
|
+
'missing-parameters': 'pass every declared parameter in params={...}; a template never guesses a default, '
|
|
1687
|
+
+ 'and action="show" lists each parameter with what it should contain',
|
|
1688
|
+
'unknown-parameters': 'remove the parameters the template does not declare, or declare them in a custom '
|
|
1689
|
+
+ 'template saved with action="save"',
|
|
1690
|
+
'builtin-template': 'built-in templates are read-only; save your version under a new id',
|
|
1691
|
+
'unknown-template': 'call action="list" to see the available template ids',
|
|
1692
|
+
}
|
|
1693
|
+
const hint = hints[error.code]
|
|
1694
|
+
?? 'call action="show" on a built-in template to see the accepted fields, then save the corrected definition'
|
|
1695
|
+
return [`[error] ${error.message}`, `hint: ${hint}`].join('\n')
|
|
1696
|
+
}
|
|
1697
|
+
|
|
1698
|
+
ctx.tools.register(defineTool({
|
|
1699
|
+
name: 'superagent_template',
|
|
1700
|
+
description:
|
|
1701
|
+
'List, show, expand, save, or delete a workflow template: a fixed goal skeleton with required parameters, '
|
|
1702
|
+
+ 'the situations it fits, and when it is the wrong tool. Expanding returns one normal goal string, which '
|
|
1703
|
+
+ 'superagent_start plans exactly like a goal typed by the user. A template cannot set limits, budgets, a '
|
|
1704
|
+
+ 'mode, or an override, so using one never widens what a run may do.',
|
|
1705
|
+
properties: {
|
|
1706
|
+
action: {
|
|
1707
|
+
type: 'string',
|
|
1708
|
+
enum: ['list', 'show', 'expand', 'save', 'delete'],
|
|
1709
|
+
description: 'List templates, show one in full, expand one into a goal, save a custom one, or delete a custom one.',
|
|
1710
|
+
},
|
|
1711
|
+
id: { type: 'string', description: 'Template id from action="list". Built-in ids are read-only.' },
|
|
1712
|
+
params: {
|
|
1713
|
+
type: 'object',
|
|
1714
|
+
description: 'Values for the placeholders (expand only). Every declared parameter is required; a missing or '
|
|
1715
|
+
+ 'empty value is refused with its name instead of being given a default.',
|
|
1716
|
+
additionalProperties: { type: 'string' },
|
|
1717
|
+
},
|
|
1718
|
+
template: {
|
|
1719
|
+
type: 'object',
|
|
1720
|
+
description: 'Complete definition (save only): id, title, whenToUse, whenNotToUse (list of strings), '
|
|
1721
|
+
+ 'variables (list of {name, description}), and skeleton with {{name}} placeholders. Unknown fields are '
|
|
1722
|
+
+ 'refused so a template cannot carry limits or overrides.',
|
|
1723
|
+
},
|
|
1724
|
+
limit: { type: 'number', description: 'Maximum templates to list (default 50).' },
|
|
1725
|
+
},
|
|
1726
|
+
required: ['action'],
|
|
1727
|
+
async execute(args = {}, exec) {
|
|
1728
|
+
const check = requireAgent(exec)
|
|
1729
|
+
if (check.error) return check.error
|
|
1730
|
+
try {
|
|
1731
|
+
await ready
|
|
1732
|
+
if (stateError) return describeError(stateError)
|
|
1733
|
+
const action = String(args.action ?? '').trim().toLowerCase()
|
|
1734
|
+
if (action === 'list') {
|
|
1735
|
+
const result = await templates.list()
|
|
1736
|
+
return formatTemplateList(result, Math.max(1, Math.min(100, Number(args.limit) || 50)))
|
|
1737
|
+
}
|
|
1738
|
+
if ((action === 'save' || action === 'delete') && memoryBlocked) {
|
|
1739
|
+
return describeError(
|
|
1740
|
+
`cannot ${action} a template: stateDir ${store.root} is inside the installed package, so writing there `
|
|
1741
|
+
+ 'would modify the shipped files; point stateDir elsewhere',
|
|
1742
|
+
)
|
|
1743
|
+
}
|
|
1744
|
+
if (action === 'show' || action === 'expand') {
|
|
1745
|
+
const id = String(args.id ?? '').trim()
|
|
1746
|
+
if (!id) return describeError(`${action} needs the id of a template; call action="list" first`)
|
|
1747
|
+
const template = await templates.get(id)
|
|
1748
|
+
if (!template) {
|
|
1749
|
+
return describeError(`no workflow template with id "${id}"; call action="list" to see the ids`)
|
|
1750
|
+
}
|
|
1751
|
+
if (action === 'show') return formatTemplateDetail(template)
|
|
1752
|
+
const expanded = expandTemplate(template, args.params)
|
|
1753
|
+
return [
|
|
1754
|
+
`expanded template "${expanded.templateId}" into one goal of ${expanded.goal.length} characters. `
|
|
1755
|
+
+ 'Start it with superagent_start goal=<the text below>; the planner sees the same goal it would '
|
|
1756
|
+
+ 'have seen if you had typed it.',
|
|
1757
|
+
'',
|
|
1758
|
+
expanded.goal,
|
|
1759
|
+
].join('\n')
|
|
1760
|
+
}
|
|
1761
|
+
if (action === 'save') {
|
|
1762
|
+
if (!args.template || typeof args.template !== 'object') {
|
|
1763
|
+
return describeError(
|
|
1764
|
+
'save needs template: the full definition (id, title, whenToUse, whenNotToUse, variables, skeleton)',
|
|
1765
|
+
)
|
|
1766
|
+
}
|
|
1767
|
+
const saved = await templates.save(args.template)
|
|
1768
|
+
return `saved template "${saved.id}"${saved.replaced ? ' (replaced the earlier version)' : ''} at ${saved.path}`
|
|
1769
|
+
}
|
|
1770
|
+
if (action === 'delete') {
|
|
1771
|
+
const id = String(args.id ?? '').trim()
|
|
1772
|
+
if (!id) return describeError('delete needs the id of a custom template; call action="list" first')
|
|
1773
|
+
const result = await templates.remove(id)
|
|
1774
|
+
return result.removed
|
|
1775
|
+
? `deleted custom template "${result.id}"; built-in templates are unaffected`
|
|
1776
|
+
: describeError(`no custom template with id "${result.id}" to delete; built-in templates cannot be deleted`)
|
|
1777
|
+
}
|
|
1778
|
+
return describeError(`unknown action "${args.action}"; use list, show, expand, save, or delete`)
|
|
1779
|
+
} catch (error) {
|
|
1780
|
+
if (error instanceof TemplateError) return templateProblem(error)
|
|
1781
|
+
return describeError(error)
|
|
1782
|
+
}
|
|
1783
|
+
},
|
|
1784
|
+
}))
|
|
1785
|
+
|
|
1786
|
+
// The embedding surface is opt-in: mounting the plugin must not open a port
|
|
1787
|
+
// unasked. When it is on, every request goes through the same orchestrator as
|
|
1788
|
+
// the tools, so quota, budgets, ownership, and cancel behave identically.
|
|
1789
|
+
if (auditor) {
|
|
1790
|
+
ctx.tools.register(defineTool({
|
|
1791
|
+
name: 'superagent_audit',
|
|
1792
|
+
description:
|
|
1793
|
+
'Query the append-only audit trail (tool calls, path writes, commands, blocks, approvals, attention '
|
|
1794
|
+
+ 'decisions, run lifecycle) for one run or a time window, or export the matching events as a single '
|
|
1795
|
+
+ 'JSONL or CSV file.',
|
|
1796
|
+
properties: {
|
|
1797
|
+
run_id: { type: 'string', description: 'Only events for this run id.' },
|
|
1798
|
+
subtask_id: { type: 'string', description: 'Only events for one subtask, e.g. "subtask-2" or "aggregator".' },
|
|
1799
|
+
kind: { type: 'string', description: 'Event kind, e.g. tool.call, path.write, command.exec, blocked, approved, attention.' },
|
|
1800
|
+
decision: { type: 'string', description: 'Only events with this decision: allow, confirm, or deny.' },
|
|
1801
|
+
result: { type: 'string', description: 'Only events with this result, e.g. ok, blocked, pending, approved, failed.' },
|
|
1802
|
+
target: { type: 'string', description: 'Substring of the path, command, or question the event is about.' },
|
|
1803
|
+
since: { type: 'string', description: 'ISO timestamp; events before it are skipped.' },
|
|
1804
|
+
until: { type: 'string', description: 'ISO timestamp; events after it are skipped.' },
|
|
1805
|
+
limit: { type: 'number', description: 'Maximum events to read or rows to print (default 8 for the summary, all for an export).' },
|
|
1806
|
+
order: { type: 'string', description: 'asc (oldest first, default) or desc.' },
|
|
1807
|
+
format: { type: 'string', description: 'summary (default), jsonl, or csv. jsonl and csv write a file and return its path.' },
|
|
1808
|
+
out_path: { type: 'string', description: 'File to write for jsonl/csv. Defaults to <stateDir>/audit/audit-export-<time>.<ext>.' },
|
|
1809
|
+
},
|
|
1810
|
+
async execute(args = {}) {
|
|
1811
|
+
try {
|
|
1812
|
+
await ready
|
|
1813
|
+
if (stateError) return describeError(stateError)
|
|
1814
|
+
const filter = {
|
|
1815
|
+
runId: args.run_id,
|
|
1816
|
+
subtaskId: args.subtask_id,
|
|
1817
|
+
kind: args.kind,
|
|
1818
|
+
decision: args.decision,
|
|
1819
|
+
result: args.result,
|
|
1820
|
+
target: args.target,
|
|
1821
|
+
since: args.since,
|
|
1822
|
+
until: args.until,
|
|
1823
|
+
limit: args.limit,
|
|
1824
|
+
order: String(args.order ?? '').toLowerCase() === 'desc' ? 'desc' : 'asc',
|
|
1825
|
+
}
|
|
1826
|
+
const format = String(args.format ?? 'summary').toLowerCase()
|
|
1827
|
+
if (format === 'jsonl' || format === 'csv') {
|
|
1828
|
+
const written = await auditor.export({ ...filter, format, outFile: args.out_path })
|
|
1829
|
+
return `exported ${written.count} event(s) to ${written.path} (${written.format}, ${formatBytes(written.bytes)})`
|
|
1830
|
+
+ (written.invalid ? `; ${written.invalid} unreadable line(s) were skipped` : '')
|
|
1831
|
+
}
|
|
1832
|
+
if (format !== 'summary') return `unknown format ${JSON.stringify(args.format)}; use summary, jsonl, or csv`
|
|
1833
|
+
const result = await auditor.query(filter)
|
|
1834
|
+
const policyError = await auditor.policyError().catch(() => null)
|
|
1835
|
+
const head = policyError
|
|
1836
|
+
? `policy: ${auditor.policyFile} is invalid, so actions are denied — `
|
|
1837
|
+
+ `${String(policyError.message ?? policyError).split('\n')[0]}\n`
|
|
1838
|
+
: ''
|
|
1839
|
+
return `${head}${formatAudit(result, { limit: Math.min(50, Math.max(1, Number(args.limit) || 8)) })}`
|
|
1840
|
+
} catch (error) {
|
|
1841
|
+
return describeError(error)
|
|
1842
|
+
}
|
|
1843
|
+
},
|
|
1844
|
+
}))
|
|
1845
|
+
}
|
|
1846
|
+
|
|
1847
|
+
if (cfg.controlPort !== null) {
|
|
1848
|
+
const clampControlWait = value => {
|
|
1849
|
+
const seconds = Number(value)
|
|
1850
|
+
if (!Number.isFinite(seconds) || seconds <= 0) return 0
|
|
1851
|
+
return Math.min(300, Math.trunc(seconds))
|
|
1852
|
+
}
|
|
1853
|
+
const control = createControlPlane({
|
|
1854
|
+
port: cfg.controlPort,
|
|
1855
|
+
stateRoot: store.root,
|
|
1856
|
+
version: pkg.version,
|
|
1857
|
+
log,
|
|
1858
|
+
actions: {
|
|
1859
|
+
// Liveness only: a probe must not sweep or reclaim runs, so this
|
|
1860
|
+
// deliberately does no state-directory work. Use GET /runs to ask what
|
|
1861
|
+
// is running.
|
|
1862
|
+
async health() {
|
|
1863
|
+
return { runs: 'GET /runs' }
|
|
1864
|
+
},
|
|
1865
|
+
async list({ limit } = {}) {
|
|
1866
|
+
await ready
|
|
1867
|
+
if (stateError) throw stateError
|
|
1868
|
+
const runs = await orchestrator.list()
|
|
1869
|
+
const stats = typeof store.stats === 'function' ? await store.stats() : null
|
|
1870
|
+
const rows = Math.max(1, Math.min(100, Number(limit) || 20))
|
|
1871
|
+
const visible = runs.slice(0, rows)
|
|
1872
|
+
return {
|
|
1873
|
+
data: { runs: visible, stats: stats ? { ...stats, root: store.root } : null },
|
|
1874
|
+
text: formatList(runs, rows, stats ? { ...stats, root: store.root } : null),
|
|
1875
|
+
}
|
|
1876
|
+
},
|
|
1877
|
+
async status(runId, waitSeconds) {
|
|
1878
|
+
await ready
|
|
1879
|
+
if (stateError) throw stateError
|
|
1880
|
+
const run = await orchestrator.status(String(runId ?? '').trim(), clampControlWait(waitSeconds))
|
|
1881
|
+
return { data: { run }, text: formatRun(run) }
|
|
1882
|
+
},
|
|
1883
|
+
async start(body = {}) {
|
|
1884
|
+
await ready
|
|
1885
|
+
if (stateError) throw stateError
|
|
1886
|
+
if (!hasSubagents()) {
|
|
1887
|
+
throw new Error(
|
|
1888
|
+
'subagent service is unavailable; dsh-superagent needs the host subagents service to create planner, '
|
|
1889
|
+
+ 'worker, and aggregator agents. Enable it in this profile (the base bundle provides it) and restart.',
|
|
1890
|
+
)
|
|
1891
|
+
}
|
|
1892
|
+
const goal = typeof body.goal === 'string' ? body.goal.trim() : ''
|
|
1893
|
+
if (!goal) {
|
|
1894
|
+
// Report the caller's mistake as written in the docs: a missing goal
|
|
1895
|
+
// is 400, not "you also did not name a session".
|
|
1896
|
+
throw new Error('goal is required; pass a concrete goal string')
|
|
1897
|
+
}
|
|
1898
|
+
const agent = resolveSession(body.session_id)
|
|
1899
|
+
const run = await orchestrator.start({
|
|
1900
|
+
goal,
|
|
1901
|
+
parentSessionId: agent.id,
|
|
1902
|
+
parent: agent,
|
|
1903
|
+
clientTimeZone: body.time_zone,
|
|
1904
|
+
allowDuplicate: body.allow_duplicate === true,
|
|
1905
|
+
mode: body.mode,
|
|
1906
|
+
queue: body.queue === true,
|
|
1907
|
+
approvePolicy: body.approve_policy === true,
|
|
1908
|
+
overrides: {
|
|
1909
|
+
maxSubtasks: body.max_subtasks,
|
|
1910
|
+
maxParallel: body.max_parallel,
|
|
1911
|
+
deadlineMinutes: body.deadline_minutes,
|
|
1912
|
+
},
|
|
1913
|
+
})
|
|
1914
|
+
const waitSeconds = clampControlWait(body.wait_seconds)
|
|
1915
|
+
if (waitSeconds > 0) {
|
|
1916
|
+
const finished = await orchestrator.status(run.id, waitSeconds)
|
|
1917
|
+
const current = run.deduped ? { ...finished, deduped: true } : finished
|
|
1918
|
+
return { data: { run: current }, text: formatRun(current) }
|
|
1919
|
+
}
|
|
1920
|
+
if (run.queue?.waiting) {
|
|
1921
|
+
return {
|
|
1922
|
+
data: { run },
|
|
1923
|
+
text: `${formatRun(run, { includeReport: false })}\n\nQueued, not started: it begins automatically when `
|
|
1924
|
+
+ `an active run finishes. Poll GET /runs/${run.id} or cancel it.`,
|
|
1925
|
+
}
|
|
1926
|
+
}
|
|
1927
|
+
return {
|
|
1928
|
+
data: { run },
|
|
1929
|
+
text: `${formatRun(run, { includeReport: false })}\n\nStarted in the background. Poll `
|
|
1930
|
+
+ `GET /runs/${run.id} or call superagent_status.`,
|
|
1931
|
+
}
|
|
1932
|
+
},
|
|
1933
|
+
async cancel(runId) {
|
|
1934
|
+
await ready
|
|
1935
|
+
if (stateError) throw stateError
|
|
1936
|
+
const run = await orchestrator.cancel(String(runId ?? '').trim())
|
|
1937
|
+
const head = run.status === 'cancelled'
|
|
1938
|
+
? `cancelled ${run.id}`
|
|
1939
|
+
: run.cancelPending
|
|
1940
|
+
? `cancel requested for ${run.id}, not confirmed by the owning process yet`
|
|
1941
|
+
: `${run.id} is ${run.status}; nothing to cancel`
|
|
1942
|
+
return { data: { run }, text: `${head}\n\n${formatRun(run, { includeReport: false })}` }
|
|
1943
|
+
},
|
|
1944
|
+
async resume(runId, body = {}) {
|
|
1945
|
+
await ready
|
|
1946
|
+
if (stateError) throw stateError
|
|
1947
|
+
if (!hasSubagents()) {
|
|
1948
|
+
throw new Error('subagent service is unavailable; resuming a run needs the host subagents service to create child agents.')
|
|
1949
|
+
}
|
|
1950
|
+
const agent = resolveSession(body.session_id)
|
|
1951
|
+
const run = await orchestrator.resume(
|
|
1952
|
+
String(runId ?? '').trim(),
|
|
1953
|
+
agent,
|
|
1954
|
+
body.time_zone,
|
|
1955
|
+
{ force: body.force === true || body.override_quota === true, approvePolicy: body.approve_policy === true },
|
|
1956
|
+
)
|
|
1957
|
+
const waitSeconds = clampControlWait(body.wait_seconds)
|
|
1958
|
+
const current = waitSeconds > 0 ? await orchestrator.status(run.id, waitSeconds) : run
|
|
1959
|
+
return { data: { run: current }, text: formatRun(current) }
|
|
1960
|
+
},
|
|
1961
|
+
},
|
|
1962
|
+
})
|
|
1963
|
+
let disposed = false
|
|
1964
|
+
const stopControl = () => {
|
|
1965
|
+
disposed = true
|
|
1966
|
+
return control.stop().catch(error => log(`cannot stop the control plane: ${error?.message ?? error}`))
|
|
1967
|
+
}
|
|
1968
|
+
if (typeof ctx.effect === 'function') {
|
|
1969
|
+
ctx.effect(() => stopControl, 'dsh-superagent control plane')
|
|
1970
|
+
} else if (typeof ctx.on === 'function') {
|
|
1971
|
+
ctx.on('dispose', stopControl)
|
|
1972
|
+
}
|
|
1973
|
+
// The state directory is created by `orchestrator.recover()`, which `ready`
|
|
1974
|
+
// awaits. Starting before it exists makes the discovery write fail with
|
|
1975
|
+
// ENOENT and would leave the plane off for the whole host lifetime.
|
|
1976
|
+
ready
|
|
1977
|
+
.then(() => {
|
|
1978
|
+
if (disposed || stateError) return null
|
|
1979
|
+
return control.start()
|
|
1980
|
+
})
|
|
1981
|
+
.catch(error => {
|
|
1982
|
+
log(
|
|
1983
|
+
`control plane is not listening: ${error?.message ?? error}; `
|
|
1984
|
+
+ 'check that controlPort is free and the state directory is writable, '
|
|
1985
|
+
+ 'or remove controlPort to keep the socket closed',
|
|
1986
|
+
)
|
|
1987
|
+
})
|
|
1988
|
+
}
|
|
1989
|
+
|
|
1990
|
+
// The workspace panel is opt-in for the same reason: mounting the plugin
|
|
1991
|
+
// must not open a socket. It reads and writes files itself, so the only
|
|
1992
|
+
// boundary that matters is the configured root, enforced in workbench.js.
|
|
1993
|
+
if (cfg.workbenchPort !== null) {
|
|
1994
|
+
const workbench = createWorkbench({
|
|
1995
|
+
port: cfg.workbenchPort,
|
|
1996
|
+
root: workbenchRoot,
|
|
1997
|
+
stateRoot: store.root,
|
|
1998
|
+
store,
|
|
1999
|
+
version: pkg.version,
|
|
2000
|
+
log,
|
|
2001
|
+
})
|
|
2002
|
+
let panelDisposed = false
|
|
2003
|
+
const stopWorkbench = () => {
|
|
2004
|
+
panelDisposed = true
|
|
2005
|
+
return workbench.stop().catch(error => log(`cannot stop the workbench: ${error?.message ?? error}`))
|
|
2006
|
+
}
|
|
2007
|
+
if (typeof ctx.effect === 'function') {
|
|
2008
|
+
ctx.effect(() => stopWorkbench, 'dsh-superagent workbench')
|
|
2009
|
+
} else if (typeof ctx.on === 'function') {
|
|
2010
|
+
ctx.on('dispose', stopWorkbench)
|
|
2011
|
+
}
|
|
2012
|
+
ready
|
|
2013
|
+
.then(() => {
|
|
2014
|
+
if (panelDisposed || stateError) return null
|
|
2015
|
+
return workbench.start()
|
|
2016
|
+
})
|
|
2017
|
+
.catch(error => {
|
|
2018
|
+
log(
|
|
2019
|
+
`workbench is not listening: ${error?.message ?? error}; `
|
|
2020
|
+
+ `check that workbenchRoot (${workbenchRoot}) exists, that workbenchPort is free, and that the state `
|
|
2021
|
+
+ 'directory is writable, or remove workbenchPort to keep the panel off',
|
|
2022
|
+
)
|
|
2023
|
+
})
|
|
2024
|
+
}
|
|
2025
|
+
|
|
2026
|
+
log(
|
|
2027
|
+
`registered ${auditor ? 11 : 10} tools; state ${store.root}`
|
|
2028
|
+
+ `${cfg.controlPort === null ? '' : `; control port ${cfg.controlPort}`}`
|
|
2029
|
+
+ `${cfg.workbenchPort === null ? '' : `; workbench ${workbenchRoot} on port ${cfg.workbenchPort}`}`,
|
|
2030
|
+
)
|
|
2031
|
+
}
|