@namzu/sdk 50.0.0 → 51.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/dist/execution/code-runtime/types.d.ts +35 -0
  3. package/dist/execution/code-runtime/types.d.ts.map +1 -1
  4. package/dist/execution/code-runtime/types.js.map +1 -1
  5. package/dist/execution/code-runtime/worker-program.d.ts +1 -1
  6. package/dist/execution/code-runtime/worker-program.d.ts.map +1 -1
  7. package/dist/execution/code-runtime/worker-program.js +72 -13
  8. package/dist/execution/code-runtime/worker-program.js.map +1 -1
  9. package/dist/execution/code-runtime/worker.d.ts.map +1 -1
  10. package/dist/execution/code-runtime/worker.js +35 -1
  11. package/dist/execution/code-runtime/worker.js.map +1 -1
  12. package/dist/execution/workflow/errors.d.ts +5 -0
  13. package/dist/execution/workflow/errors.d.ts.map +1 -0
  14. package/dist/execution/workflow/errors.js +8 -0
  15. package/dist/execution/workflow/errors.js.map +1 -0
  16. package/dist/execution/workflow/index.d.ts +9 -0
  17. package/dist/execution/workflow/index.d.ts.map +1 -0
  18. package/dist/execution/workflow/index.js +6 -0
  19. package/dist/execution/workflow/index.js.map +1 -0
  20. package/dist/execution/workflow/journal.d.ts +18 -0
  21. package/dist/execution/workflow/journal.d.ts.map +1 -0
  22. package/dist/execution/workflow/journal.js +43 -0
  23. package/dist/execution/workflow/journal.js.map +1 -0
  24. package/dist/execution/workflow/meta.d.ts +14 -0
  25. package/dist/execution/workflow/meta.d.ts.map +1 -0
  26. package/dist/execution/workflow/meta.js +314 -0
  27. package/dist/execution/workflow/meta.js.map +1 -0
  28. package/dist/execution/workflow/phases.d.ts +32 -0
  29. package/dist/execution/workflow/phases.d.ts.map +1 -0
  30. package/dist/execution/workflow/phases.js +57 -0
  31. package/dist/execution/workflow/phases.js.map +1 -0
  32. package/dist/execution/workflow/prelude.d.ts +15 -0
  33. package/dist/execution/workflow/prelude.d.ts.map +1 -0
  34. package/dist/execution/workflow/prelude.js +128 -0
  35. package/dist/execution/workflow/prelude.js.map +1 -0
  36. package/dist/execution/workflow/runtime.d.ts +31 -0
  37. package/dist/execution/workflow/runtime.d.ts.map +1 -0
  38. package/dist/execution/workflow/runtime.js +682 -0
  39. package/dist/execution/workflow/runtime.js.map +1 -0
  40. package/dist/execution/workflow/schema.d.ts +10 -0
  41. package/dist/execution/workflow/schema.d.ts.map +1 -0
  42. package/dist/execution/workflow/schema.js +145 -0
  43. package/dist/execution/workflow/schema.js.map +1 -0
  44. package/dist/execution/workflow/types.d.ts +267 -0
  45. package/dist/execution/workflow/types.d.ts.map +1 -0
  46. package/dist/execution/workflow/types.js +7 -0
  47. package/dist/execution/workflow/types.js.map +1 -0
  48. package/dist/index.d.ts +1 -0
  49. package/dist/index.d.ts.map +1 -1
  50. package/dist/index.js +1 -0
  51. package/dist/index.js.map +1 -1
  52. package/dist/plugin/shell-hook.d.ts.map +1 -1
  53. package/dist/plugin/shell-hook.js +2 -1
  54. package/dist/plugin/shell-hook.js.map +1 -1
  55. package/dist/process/kill-tree.d.ts +7 -0
  56. package/dist/process/kill-tree.d.ts.map +1 -1
  57. package/dist/process/kill-tree.js +41 -0
  58. package/dist/process/kill-tree.js.map +1 -1
  59. package/dist/provider/strict-schema.d.ts +28 -0
  60. package/dist/provider/strict-schema.d.ts.map +1 -1
  61. package/dist/provider/strict-schema.js +86 -0
  62. package/dist/provider/strict-schema.js.map +1 -1
  63. package/dist/provider/token-budget.d.ts.map +1 -1
  64. package/dist/provider/token-budget.js +31 -2
  65. package/dist/provider/token-budget.js.map +1 -1
  66. package/dist/public-runtime.d.ts +2 -1
  67. package/dist/public-runtime.d.ts.map +1 -1
  68. package/dist/public-runtime.js +4 -1
  69. package/dist/public-runtime.js.map +1 -1
  70. package/dist/public-tools.d.ts +1 -1
  71. package/dist/public-tools.d.ts.map +1 -1
  72. package/dist/public-tools.js +1 -1
  73. package/dist/public-tools.js.map +1 -1
  74. package/dist/public-types.d.ts +3 -0
  75. package/dist/public-types.d.ts.map +1 -1
  76. package/dist/runtime/jobs/job-id.d.ts +21 -0
  77. package/dist/runtime/jobs/job-id.d.ts.map +1 -0
  78. package/dist/runtime/jobs/job-id.js +66 -0
  79. package/dist/runtime/jobs/job-id.js.map +1 -0
  80. package/dist/runtime/jobs/registry.d.ts +0 -1
  81. package/dist/runtime/jobs/registry.d.ts.map +1 -1
  82. package/dist/runtime/jobs/registry.js +2 -3
  83. package/dist/runtime/jobs/registry.js.map +1 -1
  84. package/dist/runtime/query/prompt.d.ts.map +1 -1
  85. package/dist/runtime/query/prompt.js +5 -1
  86. package/dist/runtime/query/prompt.js.map +1 -1
  87. package/dist/tools/builtins/bash.d.ts +8 -1
  88. package/dist/tools/builtins/bash.d.ts.map +1 -1
  89. package/dist/tools/builtins/bash.js +20 -3
  90. package/dist/tools/builtins/bash.js.map +1 -1
  91. package/dist/tools/builtins/edit.d.ts.map +1 -1
  92. package/dist/tools/builtins/edit.js +12 -1
  93. package/dist/tools/builtins/edit.js.map +1 -1
  94. package/dist/tools/builtins/job.d.ts.map +1 -1
  95. package/dist/tools/builtins/job.js +4 -0
  96. package/dist/tools/builtins/job.js.map +1 -1
  97. package/dist/tools/builtins/wait-for-job.d.ts.map +1 -1
  98. package/dist/tools/builtins/wait-for-job.js +4 -0
  99. package/dist/tools/builtins/wait-for-job.js.map +1 -1
  100. package/dist/tools/command-shell.d.ts +55 -0
  101. package/dist/tools/command-shell.d.ts.map +1 -1
  102. package/dist/tools/command-shell.js +174 -13
  103. package/dist/tools/command-shell.js.map +1 -1
  104. package/package.json +1 -1
  105. package/src/agents/AGENTS.md +134 -46
  106. package/src/execution/code-runtime/types.ts +37 -1
  107. package/src/execution/code-runtime/worker-program.ts +72 -13
  108. package/src/execution/code-runtime/worker.ts +40 -1
  109. package/src/execution/workflow/errors.ts +7 -0
  110. package/src/execution/workflow/index.ts +8 -0
  111. package/src/execution/workflow/journal.ts +46 -0
  112. package/src/execution/workflow/meta.ts +316 -0
  113. package/src/execution/workflow/phases.ts +91 -0
  114. package/src/execution/workflow/prelude.ts +135 -0
  115. package/src/execution/workflow/runtime.ts +786 -0
  116. package/src/execution/workflow/schema.ts +137 -0
  117. package/src/execution/workflow/types.ts +300 -0
  118. package/src/index.ts +4 -0
  119. package/src/plugin/shell-hook.ts +2 -1
  120. package/src/process/kill-tree.ts +43 -0
  121. package/src/provider/strict-schema.ts +90 -0
  122. package/src/provider/token-budget.ts +31 -1
  123. package/src/public-runtime.ts +12 -0
  124. package/src/public-tools.ts +6 -0
  125. package/src/public-types.ts +3 -0
  126. package/src/runtime/jobs/job-id.ts +66 -0
  127. package/src/runtime/jobs/registry.ts +2 -3
  128. package/src/runtime/query/prompt.ts +5 -1
  129. package/src/tools/builtins/bash.ts +33 -3
  130. package/src/tools/builtins/edit.ts +12 -1
  131. package/src/tools/builtins/job.ts +4 -0
  132. package/src/tools/builtins/wait-for-job.ts +4 -0
  133. package/src/tools/command-shell.ts +194 -11
@@ -0,0 +1,137 @@
1
+ /**
2
+ * A small JSON Schema validator for `agent(..., { schema })`.
3
+ *
4
+ * Supported keywords: `type` (string or list), `enum`, `const`, `properties`,
5
+ * `required`, `additionalProperties` (boolean or schema), `items` (one
6
+ * schema), `minItems`, `maxItems`, `minLength`, `maxLength`, `minimum`,
7
+ * `maximum`, `anyOf`, `oneOf`, `allOf`. Any other keyword is ignored, and the
8
+ * schema is also handed to the host so a model-side structured-output
9
+ * mechanism can enforce more. `pattern` is deliberately not supported: the
10
+ * schema is model-authored and a regular expression is a CPU risk.
11
+ */
12
+ const MAX_DEPTH = 32
13
+
14
+ function typeOf(value: unknown): string {
15
+ if (value === null) return 'null'
16
+ if (Array.isArray(value)) return 'array'
17
+ if (typeof value === 'number') return Number.isInteger(value) ? 'integer' : 'number'
18
+ return typeof value
19
+ }
20
+
21
+ function matchesType(value: unknown, type: string): boolean {
22
+ const actual = typeOf(value)
23
+ return actual === type || (type === 'number' && actual === 'integer')
24
+ }
25
+
26
+ function same(a: unknown, b: unknown): boolean {
27
+ return JSON.stringify(a) === JSON.stringify(b)
28
+ }
29
+
30
+ function isSchema(value: unknown): value is Record<string, unknown> {
31
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
32
+ }
33
+
34
+ function check(value: unknown, schema: unknown, path: string, depth: number): string | undefined {
35
+ if (schema === true || schema === undefined) return undefined
36
+ if (schema === false) return `${path}: nothing is allowed here`
37
+ if (!isSchema(schema)) return undefined
38
+ if (depth > MAX_DEPTH) return `${path}: schema is nested too deeply`
39
+ const here = path || 'the result'
40
+
41
+ const type = schema.type
42
+ if (typeof type === 'string' && !matchesType(value, type)) {
43
+ return `${here} must be ${type}, got ${typeOf(value)}`
44
+ }
45
+ if (Array.isArray(type) && !type.some((t) => typeof t === 'string' && matchesType(value, t))) {
46
+ return `${here} must be one of ${type.join(', ')}, got ${typeOf(value)}`
47
+ }
48
+ if (Array.isArray(schema.enum) && !schema.enum.some((e) => same(e, value))) {
49
+ return `${here} must be one of ${JSON.stringify(schema.enum)}`
50
+ }
51
+ if ('const' in schema && !same(schema.const, value)) {
52
+ return `${here} must equal ${JSON.stringify(schema.const)}`
53
+ }
54
+ if (typeof value === 'string') {
55
+ if (typeof schema.minLength === 'number' && value.length < schema.minLength) {
56
+ return `${here} is shorter than ${schema.minLength} characters`
57
+ }
58
+ if (typeof schema.maxLength === 'number' && value.length > schema.maxLength) {
59
+ return `${here} is longer than ${schema.maxLength} characters`
60
+ }
61
+ }
62
+ if (typeof value === 'number') {
63
+ if (typeof schema.minimum === 'number' && value < schema.minimum) {
64
+ return `${here} is below ${schema.minimum}`
65
+ }
66
+ if (typeof schema.maximum === 'number' && value > schema.maximum) {
67
+ return `${here} is above ${schema.maximum}`
68
+ }
69
+ }
70
+ if (Array.isArray(value)) {
71
+ if (typeof schema.minItems === 'number' && value.length < schema.minItems) {
72
+ return `${here} has fewer than ${schema.minItems} items`
73
+ }
74
+ if (typeof schema.maxItems === 'number' && value.length > schema.maxItems) {
75
+ return `${here} has more than ${schema.maxItems} items`
76
+ }
77
+ if (schema.items !== undefined) {
78
+ for (const [i, item] of value.entries()) {
79
+ const problem = check(item, schema.items, `${path}[${i}]`, depth + 1)
80
+ if (problem) return problem
81
+ }
82
+ }
83
+ }
84
+ if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
85
+ const object = value as Record<string, unknown>
86
+ if (Array.isArray(schema.required)) {
87
+ for (const key of schema.required) {
88
+ if (typeof key === 'string' && !Object.hasOwn(object, key)) {
89
+ return `${here} is missing "${key}"`
90
+ }
91
+ }
92
+ }
93
+ const properties = isSchema(schema.properties) ? schema.properties : {}
94
+ for (const [key, child] of Object.entries(object)) {
95
+ const childPath = path ? `${path}.${key}` : key
96
+ if (Object.hasOwn(properties, key)) {
97
+ const problem = check(child, properties[key], childPath, depth + 1)
98
+ if (problem) return problem
99
+ } else if (schema.additionalProperties === false) {
100
+ return `${here} has an unexpected property "${key}"`
101
+ } else if (isSchema(schema.additionalProperties)) {
102
+ const problem = check(child, schema.additionalProperties, childPath, depth + 1)
103
+ if (problem) return problem
104
+ }
105
+ }
106
+ }
107
+ if (Array.isArray(schema.allOf)) {
108
+ for (const part of schema.allOf) {
109
+ const problem = check(value, part, path, depth + 1)
110
+ if (problem) return problem
111
+ }
112
+ }
113
+ if (Array.isArray(schema.anyOf) && !schema.anyOf.some((p) => !check(value, p, path, depth + 1))) {
114
+ return `${here} matches none of the allowed shapes`
115
+ }
116
+ if (Array.isArray(schema.oneOf)) {
117
+ const matching = schema.oneOf.filter((p) => !check(value, p, path, depth + 1)).length
118
+ if (matching !== 1) return `${here} must match exactly one allowed shape, matches ${matching}`
119
+ }
120
+ return undefined
121
+ }
122
+
123
+ /** `undefined` when `value` satisfies `schema`, otherwise a plain sentence naming the first problem. */
124
+ export function validateAgainstSchema(value: unknown, schema: unknown): string | undefined {
125
+ return check(value, schema, '', 0)
126
+ }
127
+
128
+ /** Parse a model's text as JSON, tolerating one surrounding code fence. */
129
+ export function parseJsonText(text: string): { ok: true; value: unknown } | { ok: false } {
130
+ const trimmed = text.trim()
131
+ const fenced = /^```(?:json)?\s*\n([\s\S]*?)\n```$/.exec(trimmed)
132
+ try {
133
+ return { ok: true, value: JSON.parse(fenced ? (fenced[1] as string) : trimmed) }
134
+ } catch {
135
+ return { ok: false }
136
+ }
137
+ }
@@ -0,0 +1,300 @@
1
+ /**
2
+ * Types of the workflow runtime: a script the model wrote once decides how
3
+ * many subagents run, with which prompts and under which phase titles; the
4
+ * runtime schedules them. See `docs/sdk/workflows.md`.
5
+ */
6
+
7
+ /** One phase declared in `meta.phases`. */
8
+ export interface WorkflowPhaseMeta {
9
+ readonly title: string
10
+ readonly detail?: string
11
+ readonly model?: string
12
+ }
13
+
14
+ /** The pure literal a script exports as `meta`. */
15
+ export interface WorkflowMeta {
16
+ readonly name: string
17
+ readonly description: string
18
+ readonly whenToUse?: string
19
+ readonly phases: readonly WorkflowPhaseMeta[]
20
+ }
21
+
22
+ /** What the host is asked to run for one `agent()` call. */
23
+ export interface WorkflowAgentRequest {
24
+ /** 1-based, in the order the script asked. */
25
+ readonly index: number
26
+ readonly label: string
27
+ readonly prompt: string
28
+ readonly phaseIndex?: number
29
+ readonly phaseTitle?: string
30
+ /** JSON Schema the result must satisfy; the runtime validates `data`. */
31
+ readonly schema?: Readonly<Record<string, unknown>>
32
+ readonly agentType?: string
33
+ readonly model?: string
34
+ readonly effort?: string
35
+ /** Report live progress; the runtime turns it into `workflow_agent` events. */
36
+ readonly onProgress: (progress: WorkflowAgentProgress) => void
37
+ }
38
+
39
+ export interface WorkflowAgentProgress {
40
+ readonly tokens?: number
41
+ readonly toolCalls?: number
42
+ readonly lastToolName?: string
43
+ readonly lastToolSummary?: string
44
+ }
45
+
46
+ /** What the host's agent run came to. */
47
+ export interface WorkflowAgentOutcome {
48
+ readonly state: 'done' | 'error' | 'skipped'
49
+ /** The agent's final text. */
50
+ readonly text?: string
51
+ /** A structured result, when the host produced one for the schema. */
52
+ readonly data?: unknown
53
+ readonly tokens: number
54
+ readonly toolCalls: number
55
+ readonly error?: string
56
+ }
57
+
58
+ /**
59
+ * Starts one subagent through the host's own delegation path (the same
60
+ * policy, sandbox, accounting and cancellation as the `Agent` tool).
61
+ * Must honour `signal`.
62
+ */
63
+ export type WorkflowSpawnAgent = (
64
+ request: WorkflowAgentRequest,
65
+ signal: AbortSignal,
66
+ ) => Promise<WorkflowAgentOutcome>
67
+
68
+ export type WorkflowAgentState = 'start' | 'progress' | 'done' | 'error'
69
+
70
+ export interface WorkflowStartedEvent {
71
+ readonly type: 'workflow_started'
72
+ readonly runId: string
73
+ readonly name: string
74
+ readonly description: string
75
+ readonly phases: readonly WorkflowPhaseMeta[]
76
+ readonly at: number
77
+ }
78
+
79
+ export interface WorkflowPhaseEvent {
80
+ readonly type: 'workflow_phase'
81
+ readonly runId: string
82
+ /** 1-based first-seen order; declared titles come first. */
83
+ readonly index: number
84
+ readonly title: string
85
+ readonly declared: boolean
86
+ readonly at: number
87
+ }
88
+
89
+ /**
90
+ * One agent changed state. `start` without `startedAt` means queued;
91
+ * `start` with `startedAt` means running. A `done` agent that was skipped
92
+ * (by the host, the operator or the token budget) carries `skipped: true`.
93
+ */
94
+ export interface WorkflowAgentEvent {
95
+ readonly type: 'workflow_agent'
96
+ readonly runId: string
97
+ readonly state: WorkflowAgentState
98
+ readonly index: number
99
+ readonly label: string
100
+ readonly phaseIndex?: number
101
+ readonly phaseTitle?: string
102
+ readonly agentType?: string
103
+ readonly model?: string
104
+ readonly queuedAt: number
105
+ readonly startedAt?: number
106
+ readonly finishedAt?: number
107
+ readonly lastProgressAt: number
108
+ readonly tokens: number
109
+ readonly toolCalls: number
110
+ readonly lastToolName?: string
111
+ readonly lastToolSummary?: string
112
+ readonly promptPreview: string
113
+ readonly resultPreview?: string
114
+ readonly error?: string
115
+ readonly skipped?: boolean
116
+ }
117
+
118
+ export interface WorkflowLogEvent {
119
+ readonly type: 'workflow_log'
120
+ readonly runId: string
121
+ readonly message: string
122
+ readonly at: number
123
+ }
124
+
125
+ export type WorkflowFinishStatus = 'completed' | 'failed' | 'stopped'
126
+
127
+ export interface WorkflowUsage {
128
+ /** Agents the script asked for and the runtime accepted. */
129
+ readonly agents: number
130
+ readonly agentsDone: number
131
+ readonly agentsFailed: number
132
+ readonly agentsSkipped: number
133
+ readonly tokens: number
134
+ readonly toolCalls: number
135
+ readonly elapsedMs: number
136
+ }
137
+
138
+ export interface WorkflowFinishedEvent {
139
+ readonly type: 'workflow_finished'
140
+ readonly runId: string
141
+ readonly status: WorkflowFinishStatus
142
+ readonly result?: unknown
143
+ readonly error?: string
144
+ readonly usage: WorkflowUsage
145
+ readonly at: number
146
+ }
147
+
148
+ export type WorkflowEvent =
149
+ | WorkflowStartedEvent
150
+ | WorkflowPhaseEvent
151
+ | WorkflowAgentEvent
152
+ | WorkflowLogEvent
153
+ | WorkflowFinishedEvent
154
+
155
+ export type WorkflowPhaseStatus = 'not-started' | 'running' | 'done' | 'failed'
156
+
157
+ export interface WorkflowPhaseSummary {
158
+ /** 0 for the derived "Agents" group, which has no phase index. */
159
+ readonly index: number
160
+ readonly title: string
161
+ readonly detail?: string
162
+ readonly status: WorkflowPhaseStatus
163
+ readonly agents: number
164
+ readonly done: number
165
+ readonly failed: number
166
+ readonly tokens: number
167
+ }
168
+
169
+ /** Append-only audit records, one JSON object per line. */
170
+ export type WorkflowJournalRecord =
171
+ | {
172
+ readonly type: 'run_started'
173
+ readonly at: number
174
+ readonly runId: string
175
+ readonly scriptSha256: string
176
+ readonly scriptBytes: number
177
+ readonly meta: WorkflowMeta
178
+ readonly args: unknown
179
+ readonly limits: WorkflowResolvedLimits
180
+ }
181
+ | {
182
+ readonly type: 'phase'
183
+ readonly at: number
184
+ readonly index: number
185
+ readonly title: string
186
+ readonly declared: boolean
187
+ }
188
+ | {
189
+ readonly type: 'agent_request'
190
+ readonly at: number
191
+ readonly index: number
192
+ readonly label: string
193
+ readonly phaseIndex?: number
194
+ readonly phaseTitle?: string
195
+ readonly promptPreview: string
196
+ readonly promptSha256: string
197
+ readonly options: {
198
+ readonly agentType?: string
199
+ readonly model?: string
200
+ readonly effort?: string
201
+ readonly schema: boolean
202
+ }
203
+ }
204
+ | {
205
+ readonly type: 'agent_outcome'
206
+ readonly at: number
207
+ readonly index: number
208
+ readonly state: 'done' | 'error' | 'skipped'
209
+ readonly tokens: number
210
+ readonly toolCalls: number
211
+ readonly queuedAt: number
212
+ readonly startedAt?: number
213
+ readonly finishedAt: number
214
+ readonly resultPreview?: string
215
+ readonly error?: string
216
+ }
217
+ | { readonly type: 'log'; readonly at: number; readonly message: string }
218
+ | {
219
+ readonly type: 'run_finished'
220
+ readonly at: number
221
+ readonly status: WorkflowFinishStatus
222
+ readonly result?: unknown
223
+ readonly error?: string
224
+ readonly usage: WorkflowUsage
225
+ }
226
+
227
+ /** Where a run's audit trail goes. Injected so the SDK stays host-agnostic. */
228
+ export interface WorkflowJournal {
229
+ /** Called once, before the first record, with the exact script text. */
230
+ writeScript?(source: string, sha256: string): Promise<void> | void
231
+ append(record: WorkflowJournalRecord): Promise<void> | void
232
+ }
233
+
234
+ export interface WorkflowLimits {
235
+ /** Agents running at once. Default `min(8, cpus - 2)`, at least 1; at most 16. */
236
+ readonly maxConcurrency?: number
237
+ /** Agents one run may start. Default 200; at most 1000. */
238
+ readonly maxAgents?: number
239
+ /** UTF-8 script size. Default 256 KiB. */
240
+ readonly maxSourceBytes?: number
241
+ /** Interpreter memory. Default 64 MiB. */
242
+ readonly memoryLimitBytes?: number
243
+ /** One value crossing the bridge, either way. Default 1 MiB. */
244
+ readonly maxValueBytes?: number
245
+ /** Stop admitting new agents once this many tokens are spent. Default: none. */
246
+ readonly tokenBudget?: number
247
+ /** Wall clock for the whole run. Default 6 hours. */
248
+ readonly maxDurationMs?: number
249
+ /** One synchronous stretch of script execution. Default 2 seconds. */
250
+ readonly cpuSliceMs?: number
251
+ /** All synchronous script execution together. Default 60 seconds. */
252
+ readonly cpuTotalMs?: number
253
+ }
254
+
255
+ export interface WorkflowResolvedLimits {
256
+ readonly maxConcurrency: number
257
+ readonly maxAgents: number
258
+ readonly maxSourceBytes: number
259
+ readonly memoryLimitBytes: number
260
+ readonly maxValueBytes: number
261
+ readonly tokenBudget?: number
262
+ readonly maxDurationMs: number
263
+ readonly cpuSliceMs: number
264
+ readonly cpuTotalMs: number
265
+ }
266
+
267
+ /** Lets the host act on one running agent. Handed to `onControl`. */
268
+ export interface WorkflowControl {
269
+ /** Skip an agent: queued ones never start, running ones are aborted. Its `agent()` resolves `null`. */
270
+ skipAgent(index: number): boolean
271
+ }
272
+
273
+ export interface WorkflowRunOptions {
274
+ /** The script, including its `export const meta` literal. Untrusted. */
275
+ readonly script: string
276
+ /** JSON handed to the script as `args`. */
277
+ readonly args?: unknown
278
+ readonly limits?: WorkflowLimits
279
+ readonly spawnAgent: WorkflowSpawnAgent
280
+ readonly journal?: WorkflowJournal
281
+ readonly signal?: AbortSignal
282
+ readonly onEvent?: (event: WorkflowEvent) => void
283
+ readonly onControl?: (control: WorkflowControl) => void
284
+ /** Default: a fresh `w` + 8 base36 id. */
285
+ readonly runId?: string
286
+ }
287
+
288
+ export interface WorkflowRunResult {
289
+ readonly runId: string
290
+ readonly status: WorkflowFinishStatus
291
+ /** What the script returned (`completed` only). */
292
+ readonly result?: unknown
293
+ readonly error?: string
294
+ readonly usage: WorkflowUsage
295
+ readonly phases: readonly WorkflowPhaseSummary[]
296
+ /** True when the script logged more than the output cap and later lines were dropped. */
297
+ readonly logsTruncated: boolean
298
+ /** Set when the journal could not be written; the run itself was not affected. */
299
+ readonly journalError?: string
300
+ }
package/src/index.ts CHANGED
@@ -19,6 +19,10 @@ export {
19
19
  UnknownBackgroundJobError,
20
20
  bindOwner,
21
21
  } from './runtime/jobs/registry.js'
22
+ export {
23
+ createBackgroundJobId,
24
+ isBackgroundJobId,
25
+ } from './runtime/jobs/job-id.js'
22
26
  export type {
23
27
  BackgroundJob,
24
28
  BackgroundJobOutput,
@@ -231,7 +231,8 @@ export function runShellHook(
231
231
  // its own — the hook's deadline becomes the grandchild's.
232
232
  detached: process.platform !== 'win32',
233
233
  // A hook has always run under `sh`, whatever shell the `bash` tool
234
- // chose. Windows has no `sh`, so there the host's own shell runs it.
234
+ // chose. Windows has no `sh`, so there the host's own shell runs it: Git Bash
235
+ // when installed, cmd.exe when not.
235
236
  ...(process.platform === 'win32'
236
237
  ? {}
237
238
  : { shell: { path: 'sh', dialect: 'sh', source: 'sh' } as const }),
@@ -1,6 +1,47 @@
1
1
  import { execFileSync } from 'node:child_process'
2
2
  import type { spawn } from 'node:child_process'
3
3
 
4
+ /**
5
+ * Git Bash children that the Windows process tree cannot reach.
6
+ *
7
+ * Git for Windows' msys runtime starts a command that is not the last of its
8
+ * line by `fork`, and the process that forked is gone by the time the command
9
+ * runs: the command's Windows parent no longer exists, so `taskkill /T` walks
10
+ * from the shell to its child and never finds the grandchild (`sleep 60; echo`,
11
+ * `cd app && npm start & wait`). Each such shell is started with a unique tag
12
+ * in its environment, which every descendant inherits however it was started;
13
+ * the tag is how the tree is found again.
14
+ */
15
+ const MSYS_SHELLS = new WeakMap<object, { readonly bash: string; readonly tag: string }>()
16
+
17
+ /** Remember how to find every process a Git Bash child started. Called by the spawn. */
18
+ export function registerMsysShell(child: object, shell: { bash: string; tag: string }): void {
19
+ MSYS_SHELLS.set(child, shell)
20
+ }
21
+
22
+ /** The environment variable that carries the tag. */
23
+ export const MSYS_TAG_VARIABLE = 'NAMZU_SHELL_TAG'
24
+
25
+ /** Kill every process whose environment carries the tag, from inside the msys runtime. */
26
+ function killMsysTagged(shell: { readonly bash: string; readonly tag: string }): void {
27
+ // `$$` is skipped so the killer cannot end itself. Parameter expansion keeps
28
+ // the script to the two programs (grep, kill) the launcher puts on PATH.
29
+ const script = [
30
+ `for f in $(grep -laF "${MSYS_TAG_VARIABLE}=${shell.tag}" /proc/[0-9]*/environ 2>/dev/null); do`,
31
+ 'p=${f#/proc/}; p=${p%/environ}; [ "$p" != "$$" ] && kill -9 $p;',
32
+ 'done',
33
+ ].join(' ')
34
+ try {
35
+ execFileSync(shell.bash, ['-c', script], {
36
+ stdio: 'ignore',
37
+ windowsHide: true,
38
+ timeout: 5000,
39
+ })
40
+ } catch {
41
+ // Nothing tagged was left, or the runtime could not start: taskkill still runs.
42
+ }
43
+ }
44
+
4
45
  /** The system's own taskkill, so a PATH entry cannot stand in for it. */
5
46
  function taskkillPath(): string {
6
47
  const root = process.env.SystemRoot ?? process.env.windir
@@ -46,6 +87,8 @@ export function killTree(child: ReturnType<typeof spawn>, signal: NodeJS.Signals
46
87
  if (!child.pid) return
47
88
  try {
48
89
  if (process.platform === 'win32') {
90
+ const msys = MSYS_SHELLS.get(child)
91
+ if (msys !== undefined) killMsysTagged(msys)
49
92
  execFileSync(taskkillPath(), ['/pid', String(child.pid), '/t', '/f'], {
50
93
  stdio: 'ignore',
51
94
  windowsHide: true,
@@ -157,6 +157,37 @@ export function findStrictSchemaViolations(schema: unknown, path = ''): StrictSc
157
157
  })
158
158
  continue
159
159
  }
160
+ // Every branch of a union has to state its `type`.
161
+ //
162
+ // `anyOf` is in the subset but its BRANCHES are still schemas, and a
163
+ // branch that says only `{ const: 'end' }` says what value it admits
164
+ // without saying what kind of value it is. Measured on the Zen
165
+ // free-tier gateway, which enforces `strict` on every model that
166
+ // reaches it: the answer is `Invalid schema for function 'edit': In
167
+ // context=('properties', 'insertLine', 'anyOf', '1'), schema must have
168
+ // a 'type' key`, and it refuses the whole request — so the tool never
169
+ // mounts and the turn dies before a single token.
170
+ //
171
+ // This is the structural half the deny-list could not see: no keyword
172
+ // here is banned, only absent. Stating the type costs nothing, because
173
+ // `{ type: 'string', const: 'end' }` admits exactly the strings the
174
+ // bare form did.
175
+ if ((keyword === 'anyOf' || keyword === 'allOf') && Array.isArray(value)) {
176
+ for (const [index, branch] of value.entries()) {
177
+ if (
178
+ typeof branch !== 'object' ||
179
+ branch === null ||
180
+ Array.isArray(branch) ||
181
+ !('type' in branch)
182
+ ) {
183
+ found.push({
184
+ path: `${here}[${index}]`,
185
+ keyword,
186
+ remedy: 'state a `type` on every branch of a union',
187
+ })
188
+ }
189
+ }
190
+ }
160
191
  found.push(...findStrictSchemaViolations(value, here))
161
192
  }
162
193
  return found
@@ -180,3 +211,62 @@ export function assertStrictSchema(toolName: string, schema: unknown): void {
180
211
  `Tool "${toolName}" is marked for strict input validation, but its model-facing schema uses ${violations.length} construct(s) the strict subset does not accept. The request would be rejected whole, taking every other tool in it down as well.\n${detail}`,
181
212
  )
182
213
  }
214
+
215
+ /**
216
+ * Whether a wire enforcing `strict` would actually take this schema.
217
+ *
218
+ * Wider than {@link findStrictSchemaViolations}, and the difference is not
219
+ * redundancy. That function answers "can this schema be SAID in the strict
220
+ * dialect" — it denies keywords the dialect has no spelling for, and it is
221
+ * what registration checks, because a schema that fails it could never be
222
+ * sent anywhere. A schema can pass it and still be REFUSED by a wire that
223
+ * applies the dialect's structural rules on top, and the two questions have
224
+ * different owners: registration decides whether a tool may ask for the
225
+ * guarantee at all, a driver decides whether to claim it on THIS wire.
226
+ *
227
+ * The structural rule measured here: every object that declares `properties`
228
+ * must list all of them in `required`. The Zen free-tier gateway says so in
229
+ * as many words — `In context=('properties', 'edits', 'items'), 'required' is
230
+ * required to be supplied and to be an array including every key in
231
+ * properties` — and it refuses the WHOLE request, so one optional field in one
232
+ * tool takes every other tool in the call down with it.
233
+ *
234
+ * That is why a driver must ask rather than assume. Namzu's tool contracts are
235
+ * written with optional fields, on purpose: `edit` accepts a find-and-replace
236
+ * OR an insertion, and saying "either, never both" as `required` on a union
237
+ * would be a worse schema, not a stricter one. So the schema stays as it is
238
+ * and the driver stops vouching for a guarantee the wire cannot carry — the
239
+ * same call the Zen driver already makes for the Responses wire, and the one
240
+ * OpenCode makes for every tool on this gateway (`strict: false`).
241
+ */
242
+ export function acceptsStrictSchema(schema: unknown): boolean {
243
+ // A missing schema cannot be vouched for. `findStrictSchemaViolations`
244
+ // walks nothing in `undefined` and finds nothing, so without this the
245
+ // predicate would answer `true` for a tool that declared no schema at all
246
+ // — and the driver would put `strict: true` on a wire whose `parameters`
247
+ // came from somewhere else entirely.
248
+ if (typeof schema !== 'object' || schema === null || Array.isArray(schema)) return false
249
+ if (findStrictSchemaViolations(schema).length > 0) return false
250
+ return !hasUngatedProperties(schema)
251
+ }
252
+
253
+ /**
254
+ * Whether any object declares `properties` without requiring all of them.
255
+ */
256
+ function hasUngatedProperties(node: unknown): boolean {
257
+ if (Array.isArray(node)) return node.some((item) => hasUngatedProperties(item))
258
+ if (typeof node !== 'object' || node === null) return false
259
+
260
+ const record = node as Record<string, unknown>
261
+ const properties = record.properties
262
+ if (
263
+ typeof properties === 'object' &&
264
+ properties !== null &&
265
+ !Array.isArray(properties) &&
266
+ (!Array.isArray(record.required) ||
267
+ Object.keys(properties).some((key) => !(record.required as unknown[]).includes(key)))
268
+ )
269
+ return true
270
+
271
+ return Object.values(record).some((value) => hasUngatedProperties(value))
272
+ }
@@ -1,8 +1,10 @@
1
+ import { estimateMessagesTokens } from '../compaction/token-estimate.js'
1
2
  import { EMPTY_TOKEN_USAGE } from '../constants/limits.js'
2
3
  import type { SessionTokenBudget } from '../store/budget/ledger.js'
3
4
  import { type TokenUsage, mergeTokenUsage } from '../types/common/index.js'
4
5
  import { ProviderError, classifyProviderError } from '../types/provider/errors.js'
5
6
  import type { LLMProvider, StreamChunk } from '../types/provider/index.js'
7
+ import { cancelCauseOf } from '../types/session/cancel-cause.js'
6
8
  import { isProviderRequestError } from './errors.js'
7
9
 
8
10
  export class TokenBudgetAdmissionError extends ProviderError {
@@ -49,6 +51,7 @@ export function withTokenBudget(provider: LLMProvider, budget: SessionTokenBudge
49
51
  let completed = false
50
52
  let outputObserved = false
51
53
  let uncertainRetry = false
54
+ let streamedChars = 0
52
55
  let contacted = false
53
56
  let abandoned = false
54
57
  let iterator: AsyncIterator<StreamChunk> | undefined
@@ -107,6 +110,7 @@ export function withTokenBudget(provider: LLMProvider, budget: SessionTokenBudge
107
110
  })
108
111
  }
109
112
  if (Object.keys(chunk.delta).length > 0) outputObserved = true
113
+ if (typeof chunk.delta.content === 'string') streamedChars += chunk.delta.content.length
110
114
  if (chunk.error) throw new Error(chunk.error)
111
115
  yield chunk
112
116
  }
@@ -142,7 +146,33 @@ export function withTokenBudget(provider: LLMProvider, budget: SessionTokenBudge
142
146
  } catch {
143
147
  // Cleanup cannot replace the provider outcome.
144
148
  }
145
- if (!completed) await budget.failRequest(requestId, usage)
149
+ if (!completed) {
150
+ // A request the operator deliberately cancelled (a `user` cancel cause,
151
+ // not a parent or a runtime tearing the tree down) before any usage frame
152
+ // arrived is closed on an estimate (the prompt and what streamed), not
153
+ // left as unknown spend. Left open it poisons the whole tree: every
154
+ // sibling and every later child is refused for the rest of the turn,
155
+ // because of work somebody chose to stop. The estimate can under-count
156
+ // what the provider billed for the part it never reported; a failure
157
+ // that was not a cancellation keeps its marker as before.
158
+ if (
159
+ usage === undefined &&
160
+ signal?.aborted === true &&
161
+ cancelCauseOf(signal.reason) === 'user' &&
162
+ !uncertainRetry
163
+ ) {
164
+ const prompt = estimateMessagesTokens(params.messages)
165
+ const completion = Math.ceil(streamedChars / 4)
166
+ await budget.finishRequest(requestId, {
167
+ ...EMPTY_TOKEN_USAGE,
168
+ promptTokens: prompt,
169
+ completionTokens: completion,
170
+ totalTokens: prompt + completion,
171
+ })
172
+ } else {
173
+ await budget.failRequest(requestId, usage)
174
+ }
175
+ }
146
176
  }
147
177
  }
148
178