@namzu/sdk 75.0.0 → 76.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 (100) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/dist/bridge/acp/server.d.ts.map +1 -1
  3. package/dist/bridge/acp/server.js +4 -1
  4. package/dist/bridge/acp/server.js.map +1 -1
  5. package/dist/bridge/acp/update.d.ts.map +1 -1
  6. package/dist/bridge/acp/update.js +22 -2
  7. package/dist/bridge/acp/update.js.map +1 -1
  8. package/dist/peers/record.d.ts +3 -3
  9. package/dist/public-runtime.d.ts +2 -2
  10. package/dist/public-runtime.d.ts.map +1 -1
  11. package/dist/public-runtime.js +1 -1
  12. package/dist/public-runtime.js.map +1 -1
  13. package/dist/runtime/query/executor.d.ts.map +1 -1
  14. package/dist/runtime/query/executor.js +10 -1
  15. package/dist/runtime/query/executor.js.map +1 -1
  16. package/dist/session/workspace/git-worktree.d.ts +18 -0
  17. package/dist/session/workspace/git-worktree.d.ts.map +1 -1
  18. package/dist/session/workspace/git-worktree.js +100 -1
  19. package/dist/session/workspace/git-worktree.js.map +1 -1
  20. package/dist/session/workspace/index.d.ts +1 -1
  21. package/dist/session/workspace/index.d.ts.map +1 -1
  22. package/dist/session/workspace/index.js +1 -1
  23. package/dist/session/workspace/index.js.map +1 -1
  24. package/dist/store/checkpoint/contract.d.ts.map +1 -1
  25. package/dist/store/checkpoint/contract.js +5 -2
  26. package/dist/store/checkpoint/contract.js.map +1 -1
  27. package/dist/store/session-log/core.d.ts.map +1 -1
  28. package/dist/store/session-log/core.js +30 -1
  29. package/dist/store/session-log/core.js.map +1 -1
  30. package/dist/tools/admit-facts.d.ts.map +1 -1
  31. package/dist/tools/admit-facts.js +19 -0
  32. package/dist/tools/admit-facts.js.map +1 -1
  33. package/dist/tools/builtins/bash.d.ts +1 -1
  34. package/dist/tools/builtins/bash.d.ts.map +1 -1
  35. package/dist/tools/builtins/bash.js +9 -7
  36. package/dist/tools/builtins/bash.js.map +1 -1
  37. package/dist/tools/builtins/browser.d.ts +2 -2
  38. package/dist/tools/builtins/browser.d.ts.map +1 -1
  39. package/dist/tools/builtins/browser.js +15 -3
  40. package/dist/tools/builtins/browser.js.map +1 -1
  41. package/dist/tools/builtins/computer-use.d.ts +19 -3
  42. package/dist/tools/builtins/computer-use.d.ts.map +1 -1
  43. package/dist/tools/builtins/computer-use.js +150 -50
  44. package/dist/tools/builtins/computer-use.js.map +1 -1
  45. package/dist/tools/coordinator/agent.d.ts.map +1 -1
  46. package/dist/tools/coordinator/agent.js +6 -0
  47. package/dist/tools/coordinator/agent.js.map +1 -1
  48. package/dist/tools/coordinator/index.d.ts.map +1 -1
  49. package/dist/tools/coordinator/index.js +6 -0
  50. package/dist/tools/coordinator/index.js.map +1 -1
  51. package/dist/tools/coordinator/progress.d.ts +9 -0
  52. package/dist/tools/coordinator/progress.d.ts.map +1 -0
  53. package/dist/tools/coordinator/progress.js +30 -0
  54. package/dist/tools/coordinator/progress.js.map +1 -0
  55. package/dist/tools/shell-output-window.d.ts +12 -0
  56. package/dist/tools/shell-output-window.d.ts.map +1 -0
  57. package/dist/tools/shell-output-window.js +92 -0
  58. package/dist/tools/shell-output-window.js.map +1 -0
  59. package/dist/types/acp/index.d.ts +3 -0
  60. package/dist/types/acp/index.d.ts.map +1 -1
  61. package/dist/types/browser/index.d.ts +4 -0
  62. package/dist/types/browser/index.d.ts.map +1 -1
  63. package/dist/types/computer-use/index.d.ts +4 -0
  64. package/dist/types/computer-use/index.d.ts.map +1 -1
  65. package/dist/types/session/checkpoint.d.ts +13 -0
  66. package/dist/types/session/checkpoint.d.ts.map +1 -1
  67. package/dist/types/session/checkpoint.js +33 -0
  68. package/dist/types/session/checkpoint.js.map +1 -1
  69. package/dist/types/session/events.d.ts +3 -0
  70. package/dist/types/session/events.d.ts.map +1 -1
  71. package/dist/types/session/events.js.map +1 -1
  72. package/dist/types/tool/index.d.ts +15 -0
  73. package/dist/types/tool/index.d.ts.map +1 -1
  74. package/dist/types/tool/index.js.map +1 -1
  75. package/dist/types/tool/presentation.d.ts +8 -0
  76. package/dist/types/tool/presentation.d.ts.map +1 -1
  77. package/package.json +1 -1
  78. package/src/bridge/acp/server.ts +6 -1
  79. package/src/bridge/acp/update.ts +23 -2
  80. package/src/public-runtime.ts +2 -0
  81. package/src/runtime/query/executor.ts +12 -3
  82. package/src/session/workspace/git-worktree.ts +115 -1
  83. package/src/session/workspace/index.ts +6 -1
  84. package/src/store/checkpoint/contract.ts +9 -2
  85. package/src/store/session-log/core.ts +34 -1
  86. package/src/tools/admit-facts.ts +20 -0
  87. package/src/tools/builtins/bash.ts +11 -12
  88. package/src/tools/builtins/browser.ts +16 -3
  89. package/src/tools/builtins/computer-use.ts +188 -44
  90. package/src/tools/coordinator/agent.ts +6 -0
  91. package/src/tools/coordinator/index.ts +6 -0
  92. package/src/tools/coordinator/progress.ts +40 -0
  93. package/src/tools/shell-output-window.ts +97 -0
  94. package/src/types/acp/index.ts +3 -0
  95. package/src/types/browser/index.ts +2 -0
  96. package/src/types/computer-use/index.ts +17 -0
  97. package/src/types/session/checkpoint.ts +37 -0
  98. package/src/types/session/events.ts +3 -0
  99. package/src/types/tool/index.ts +10 -0
  100. package/src/types/tool/presentation.ts +12 -1
@@ -1,6 +1,11 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks'
1
2
  import { createHash } from 'node:crypto'
2
3
  import { z } from 'zod'
3
4
  import { modelReadsImages, resolveProviderCapabilities } from '../../provider/capabilities.js'
5
+ import type {
6
+ ComputerUseStageTimes,
7
+ ComputerUseTimingStage,
8
+ } from '../../types/computer-use/index.js'
4
9
  import type {
5
10
  ActionDelivery,
6
11
  ActionRetrySafety,
@@ -75,6 +80,7 @@ async function settleAfterActions(
75
80
  windowId: string | undefined,
76
81
  settleMs: number,
77
82
  signal: AbortSignal | undefined,
83
+ wait: (run: () => Promise<void>) => Promise<void>,
78
84
  ): Promise<void> {
79
85
  if (settleMs > 0 && typeof host.settle === 'function') {
80
86
  try {
@@ -87,7 +93,7 @@ async function settleAfterActions(
87
93
  // Fall through to the fixed wait; a cancelled signal makes it reject at once.
88
94
  }
89
95
  }
90
- await sleep(settleMs, signal)
96
+ await wait(() => sleep(settleMs, signal))
91
97
  }
92
98
  const MAX_LISTED_WINDOWS = 50
93
99
  /** Steps after which a batch may end with the window's controls instead of a picture. */
@@ -153,11 +159,58 @@ const ADVICE_MIN_MARGIN = 0.4
153
159
  /** The most controls an advisor is asked about at once. */
154
160
  const MAX_ADVISED_CANDIDATES = 255
155
161
 
162
+ /** Operator diagnostics for one computer-use call. */
163
+ export interface ComputerUseTimingRecord {
164
+ readonly app?: string
165
+ readonly elapsedMs: number
166
+ readonly stages: ComputerUseStageTimes
167
+ readonly steps: readonly {
168
+ readonly action: string
169
+ readonly elapsedMs: number
170
+ readonly stages: ComputerUseStageTimes
171
+ }[]
172
+ }
173
+
174
+ function timingTail(
175
+ elapsedMs: number,
176
+ stages: ComputerUseStageTimes,
177
+ steps: ComputerUseTimingRecord['steps'],
178
+ ): string {
179
+ const totals = { ...stages }
180
+ for (const step of steps) {
181
+ for (const stage of Object.keys(step.stages) as ComputerUseTimingStage[]) {
182
+ totals[stage] = (totals[stage] ?? 0) + (step.stages[stage] ?? 0)
183
+ }
184
+ }
185
+ const labels = {
186
+ verify_reads: 'verify',
187
+ settle_wait: 'settle',
188
+ ui_snapshot: 'tree',
189
+ capture_encode: 'capture',
190
+ list_windows: 'windows',
191
+ input_delivery: 'input',
192
+ foreground_gate: 'foreground',
193
+ } satisfies Record<ComputerUseTimingStage, string>
194
+ const detail = (Object.keys(totals) as ComputerUseTimingStage[])
195
+ .sort((a, b) => (totals[b] ?? 0) - (totals[a] ?? 0))
196
+ .slice(0, 3)
197
+ .map((stage) => `${labels[stage]} ${((totals[stage] ?? 0) / 1000).toFixed(1)}`)
198
+ return `took ${(elapsedMs / 1000).toFixed(1)}s${detail.length ? ` (${detail.join(', ')})` : ''}`
199
+ }
200
+
156
201
  /**
157
202
  * How `createComputerUseTool` sizes screenshots, paces actions and bounds a
158
203
  * batch. Every field is optional.
159
204
  */
160
205
  export interface ComputerUseToolOptions {
206
+ /** Operator-only timing report. Defaults to on. */
207
+ readonly timings?: boolean | (() => boolean)
208
+ /** Receives one timing record after each call, including failures. */
209
+ readonly onTiming?: (
210
+ record: ComputerUseTimingRecord,
211
+ context: ToolContext,
212
+ ) => void | Promise<void>
213
+
161
214
  /**
162
215
  * A second opinion on which control an intent names; see
163
216
  * {@link ComputerUseAdvisor}. With one that `acts`, the tool offers `ui_do`
@@ -1868,6 +1921,40 @@ export function createComputerUseTool(
1868
1921
  // passes it so an interrupted turn stops waiting for the desktop.
1869
1922
  let callSignal: AbortSignal | undefined
1870
1923
 
1924
+ const timing = new AsyncLocalStorage<{
1925
+ stages: ComputerUseStageTimes
1926
+ steps: ComputerUseTimingRecord['steps'][number][]
1927
+ }>()
1928
+ const measure = async <T>(stage: ComputerUseTimingStage, run: () => Promise<T>): Promise<T> => {
1929
+ const store = timing.getStore()
1930
+ if (!store) return run()
1931
+ const start = performance.now()
1932
+ try {
1933
+ return await run()
1934
+ } finally {
1935
+ store.stages[stage] = (store.stages[stage] ?? 0) + performance.now() - start
1936
+ }
1937
+ }
1938
+ const timeStep = async <T>(action: string, run: () => Promise<T>): Promise<T> => {
1939
+ const store = timing.getStore()
1940
+ if (!store) return run()
1941
+ const stages: ComputerUseStageTimes = {}
1942
+ const start = performance.now()
1943
+ try {
1944
+ return await timing.run({ stages, steps: store.steps }, run)
1945
+ } finally {
1946
+ store.steps.push({ action, elapsedMs: performance.now() - start, stages })
1947
+ }
1948
+ }
1949
+ const settle = (window: string | undefined, signal?: AbortSignal) =>
1950
+ host.withTiming
1951
+ ? settleAfterActions(host, window, settings.settleMs, signal, (wait) =>
1952
+ measure('settle_wait', wait),
1953
+ )
1954
+ : measure('settle_wait', () =>
1955
+ settleAfterActions(host, window, settings.settleMs, signal, (wait) => wait()),
1956
+ )
1957
+
1871
1958
  /** Capture the display or one explicitly named window, fit it, and number it. */
1872
1959
  const capture = async (windowId?: string): Promise<Capture> => {
1873
1960
  if (windowId !== undefined) {
@@ -1879,7 +1966,7 @@ export function createComputerUseTool(
1879
1966
  windowId,
1880
1967
  callSignal,
1881
1968
  )
1882
- const image = await fitPng(shot.data, settings.limits())
1969
+ const image = await measure('capture_encode', () => fitPng(shot.data, settings.limits()))
1883
1970
  if (image.sourceWidth !== shot.width || image.sourceHeight !== shot.height)
1884
1971
  throw new StepFailure(
1885
1972
  'the window PNG dimensions changed during capture; take a new screenshot',
@@ -1896,7 +1983,7 @@ export function createComputerUseTool(
1896
1983
  if (result.type !== 'screenshot')
1897
1984
  throw new Error(`computer_use: the host answered a screenshot with "${result.type}"`)
1898
1985
  const shot = result.result
1899
- const image = await fitPng(shot.data, settings.limits())
1986
+ const image = await measure('capture_encode', () => fitPng(shot.data, settings.limits()))
1900
1987
  const display = shot.display ?? assumedDisplay(image.sourceWidth, image.sourceHeight)
1901
1988
  const frame = frames.record(image, display)
1902
1989
  noteDigest(frame, image)
@@ -2974,7 +3061,7 @@ export function createComputerUseTool(
2974
3061
  fitted = await cropAndFitPng(frame.window.data, rect, settings.limits())
2975
3062
  } else if (caps.regionCapture === true && typeof host.captureRegion === 'function') {
2976
3063
  const piece = await host.captureRegion(rect, callSignal)
2977
- fitted = await fitPng(piece.data, settings.limits())
3064
+ fitted = await measure('capture_encode', () => fitPng(piece.data, settings.limits()))
2978
3065
  } else {
2979
3066
  const result = await host.execute({ type: 'screenshot' }, callSignal)
2980
3067
  if (result.type !== 'screenshot')
@@ -3134,6 +3221,26 @@ export function createComputerUseTool(
3134
3221
  break
3135
3222
  }
3136
3223
  try {
3224
+ await timeStep(step.item.type, runStep)
3225
+ } catch (error) {
3226
+ const unknown = error instanceof StepFailure ? error.unknown : undefined
3227
+ const delivery = error instanceof StepFailure ? error.delivery : undefined
3228
+ const retrySafety = error instanceof StepFailure ? error.retrySafety : undefined
3229
+ const message = signal?.aborted ? 'cancelled' : errorText(error)
3230
+ failure = { index, error: message, ...(unknown ? { unknown } : {}) }
3231
+ records.push({
3232
+ label: step.label,
3233
+ status: 'failed',
3234
+ error: message,
3235
+ ...(unknown ? { unknown } : {}),
3236
+ ...(delivery ? { delivery } : {}),
3237
+ ...(retrySafety ? { retrySafety } : {}),
3238
+ })
3239
+ if (delivery === 'delivered_unverified' || unknown) changed = true
3240
+ break
3241
+ }
3242
+
3243
+ async function runStep(): Promise<void> {
3137
3244
  const keyboard = step.item.type === 'type_text' || step.item.type === 'key'
3138
3245
  if (keyboard && !actionFrame?.window && !frontChecked) {
3139
3246
  await refuseTerminalInFront()
@@ -3167,24 +3274,6 @@ export function createComputerUseTool(
3167
3274
  postWindowId = actionFrame.window.window.id
3168
3275
  records.push({ label: step.label, status: 'done', ...outcome })
3169
3276
  if (step.mutating) changed = true
3170
- } catch (error) {
3171
- const unknown = error instanceof StepFailure ? error.unknown : undefined
3172
- const delivery = error instanceof StepFailure ? error.delivery : undefined
3173
- const retrySafety = error instanceof StepFailure ? error.retrySafety : undefined
3174
- const message = signal?.aborted ? 'cancelled' : errorText(error)
3175
- failure = { index, error: message, ...(unknown ? { unknown } : {}) }
3176
- records.push({
3177
- label: step.label,
3178
- status: 'failed',
3179
- error: message,
3180
- ...(unknown ? { unknown } : {}),
3181
- ...(delivery ? { delivery } : {}),
3182
- ...(retrySafety ? { retrySafety } : {}),
3183
- })
3184
- // A step that may have acted changed the desktop even though it failed.
3185
- if (delivery === 'delivered_unverified') changed = true
3186
- if (unknown) changed = true
3187
- break
3188
3277
  }
3189
3278
  }
3190
3279
  for (const step of planned.slice(records.length))
@@ -3197,7 +3286,7 @@ export function createComputerUseTool(
3197
3286
  let frameShot: Capture | undefined
3198
3287
  if (unsent.length > 0 && !failure && !signal?.aborted) {
3199
3288
  try {
3200
- if (changed) await settleAfterActions(host, undefined, settings.settleMs, signal)
3289
+ if (changed) await settle(undefined, signal)
3201
3290
  frameShot = await capture()
3202
3291
  const before = single
3203
3292
  ? ''
@@ -3258,7 +3347,7 @@ export function createComputerUseTool(
3258
3347
  }
3259
3348
  if (treeEnding && postWindowId !== undefined) {
3260
3349
  try {
3261
- await settleAfterActions(host, postWindowId, settings.settleMs, signal)
3350
+ await settle(postWindowId, signal)
3262
3351
  const read = await uiSnapshot({
3263
3352
  type: 'ui_snapshot',
3264
3353
  window_id: postWindowId,
@@ -3288,7 +3377,7 @@ export function createComputerUseTool(
3288
3377
  }
3289
3378
  if (looks && treeText === undefined && windowClosed === undefined) {
3290
3379
  try {
3291
- await settleAfterActions(host, postWindowId, settings.settleMs, signal)
3380
+ await settle(postWindowId, signal)
3292
3381
  shot = await capture(postWindowId)
3293
3382
  } catch (error) {
3294
3383
  shotError = signal?.aborted ? 'cancelled' : errorText(error)
@@ -3798,13 +3887,15 @@ export function createComputerUseTool(
3798
3887
  try {
3799
3888
  switch (input.type) {
3800
3889
  case 'screenshot':
3801
- return await firstLookWithTree(await capture(input.window_id), input.window_id)
3890
+ return await timeStep(input.type, async () =>
3891
+ firstLookWithTree(await capture(input.window_id), input.window_id),
3892
+ )
3802
3893
  case 'zoom':
3803
- return await zoom(input)
3894
+ return await timeStep(input.type, () => zoom(input))
3804
3895
  case 'ui_snapshot':
3805
- return await uiSnapshot(input)
3896
+ return await timeStep(input.type, () => uiSnapshot(input))
3806
3897
  case 'wait_for':
3807
- return await waitFor(input, context)
3898
+ return await timeStep(input.type, () => waitFor(input, context))
3808
3899
  case 'batch':
3809
3900
  return await runSteps(input.actions, input.screenshot_id, context, false)
3810
3901
  default: {
@@ -3849,37 +3940,90 @@ export function createComputerUseTool(
3849
3940
  presentResult: (_input, result) => {
3850
3941
  // The first call to work on an application says so, so a person reading the
3851
3942
  // conversation can see which applications this conversation has used.
3852
- const first = isRecord(result.data) ? result.data.firstUseOf : undefined
3943
+ const data = isRecord(result.data) ? result.data : undefined
3944
+ const first = data?.firstUseOf
3945
+ const tail = typeof data?.timingTail === 'string' ? data.timingTail : undefined
3853
3946
  if (result.success && typeof first === 'string')
3854
3947
  return {
3855
3948
  kind: 'generic',
3856
- label: `Using ${applicationName(first)}`,
3949
+ label: `Using ${applicationName(first)}${tail ? ` · ${tail}` : ''}`,
3857
3950
  presentation: 'activity',
3858
3951
  }
3952
+ if (tail)
3953
+ return {
3954
+ kind: 'terminal',
3955
+ output: [result.success ? result.output : (result.error ?? result.output), tail]
3956
+ .filter(Boolean)
3957
+ .join('\n'),
3958
+ }
3859
3959
  return result.success && ACKNOWLEDGEMENT.test(result.output)
3860
3960
  ? { kind: 'generic', label: result.output, visibility: 'hidden' }
3861
3961
  : undefined
3862
3962
  },
3863
3963
 
3864
3964
  async execute(input, context): Promise<ToolResult> {
3865
- const keptOut = await deniedAppRefusal(input, context)
3866
- if (keptOut) return { success: false, output: '', error: keptOut }
3867
- const tiered = await appTierRefusal(input, context)
3868
- if (tiered) return { success: false, output: '', error: tiered }
3869
- const shotId = 'screenshot_id' in input ? input.screenshot_id : undefined
3870
- const before = shotId ? frames.get(shotId) : frames.latest()
3871
- // Only what is already known: acting must not cost the host a call it would not make.
3872
- const app = appKnown(input)
3873
- const result = await runAction(input, context)
3874
- if (app && result.success !== false && !appsUsed.has(app) && !isReadOnlyInput(input)) {
3875
- appsUsed.add(app)
3965
+ const show =
3966
+ typeof options.timings === 'function' ? options.timings() : options.timings !== false
3967
+ if (!options.onTiming && (!show || !host.withTiming)) return execute()
3968
+ const stages: ComputerUseStageTimes = {}
3969
+ const steps: ComputerUseTimingRecord['steps'][number][] = []
3970
+ const start = performance.now()
3971
+ let elapsedMs: number
3972
+ let result: ToolResult
3973
+ try {
3974
+ result = await timing.run(
3975
+ { stages, steps },
3976
+ () =>
3977
+ host.withTiming?.((stage, ms) => {
3978
+ const current = timing.getStore()?.stages
3979
+ if (current) current[stage] = (current[stage] ?? 0) + ms
3980
+ }, execute) ?? execute(),
3981
+ )
3982
+ } finally {
3983
+ elapsedMs = performance.now() - start
3984
+ const record = { app: appKnown(input), elapsedMs, stages, steps }
3985
+ try {
3986
+ await options.onTiming?.(
3987
+ {
3988
+ ...(record.app ? { app: record.app } : {}),
3989
+ elapsedMs,
3990
+ stages,
3991
+ steps,
3992
+ },
3993
+ context,
3994
+ )
3995
+ } catch {
3996
+ // Diagnostics must never change an input's outcome.
3997
+ }
3998
+ }
3999
+ if (show) {
3876
4000
  result.data = {
3877
4001
  ...(isRecord(result.data) ? result.data : {}),
3878
- firstUseOf: app,
4002
+ timingTail: timingTail(elapsedMs, stages, steps),
3879
4003
  }
3880
4004
  }
3881
- await observe(input, before, result, context.toolUseId, app)
3882
4005
  return result
4006
+
4007
+ async function execute(): Promise<ToolResult> {
4008
+ const keptOut = await deniedAppRefusal(input, context)
4009
+ if (keptOut) return { success: false, output: '', error: keptOut }
4010
+ const tiered = await appTierRefusal(input, context)
4011
+ if (tiered) return { success: false, output: '', error: tiered }
4012
+ const shotId = 'screenshot_id' in input ? input.screenshot_id : undefined
4013
+ const before = shotId ? frames.get(shotId) : frames.latest()
4014
+ // Only what is already known: acting must not cost the host a call it would not make.
4015
+ const app = appKnown(input)
4016
+ const result = await runAction(input, context)
4017
+ if (app && result.success !== false && !appsUsed.has(app) && !isReadOnlyInput(input)) {
4018
+ appsUsed.add(app)
4019
+ result.data = {
4020
+ ...(isRecord(result.data) ? result.data : {}),
4021
+ firstUseOf: app,
4022
+ }
4023
+ }
4024
+ await observe(input, before, result, context.toolUseId, app)
4025
+ return result
4026
+ }
3883
4027
  },
3884
4028
  })
3885
4029
  const browserQuestionPending = (app: string): boolean =>
@@ -8,6 +8,7 @@ import { defineTool } from '../defineTool.js'
8
8
  import { KERNEL_RECORD_PREFIX, wrapUntrusted } from '../untrusted-envelope.js'
9
9
  import { describeOutcomeRecord } from './outcome-record.js'
10
10
  import { failureLabel, taskSucceeded } from './outcome.js'
11
+ import { delegationFacts, delegationProgress } from './progress.js'
11
12
 
12
13
  import { DELEGATION_TIMEOUT_MS } from './index.js'
13
14
  import type { TaskLaunchedCallback } from './index.js'
@@ -82,6 +83,7 @@ export function buildAgentTool(opts: AgentToolOptions): ToolDefinition {
82
83
 
83
84
  return defineTool({
84
85
  name: 'Agent',
86
+ presentCall: ({ description }) => ({ kind: 'generic', label: description.slice(0, 240) }),
85
87
  description: `Delegate a task to a specialized subagent. BLOCKING: returns when the subagent has finished, with the subagent's final text as the tool result. The subagent runs in its own context window and cannot see your conversation — include all necessary context in the prompt. Available subagents: ${agentIds.join(', ')}. To run multiple subagents in parallel, call this tool multiple times in a single response.`,
86
88
  inputSchema: z.object({
87
89
  description: z.string().describe('Short label for tracking (shown to the user)'),
@@ -150,6 +152,7 @@ export function buildAgentTool(opts: AgentToolOptions): ToolDefinition {
150
152
  agentId,
151
153
  prompt,
152
154
  workingDirectory: cwd,
155
+ onEvent: delegationProgress(context),
153
156
  runtimeContext: opts.runtimeContext,
154
157
  // Hang the child off the executing tool's span, so the
155
158
  // delegation appears inside the turn that asked for it rather
@@ -203,6 +206,7 @@ export function buildAgentTool(opts: AgentToolOptions): ToolDefinition {
203
206
  // it: a review caught this site, and nothing carried the answer to
204
207
  // the other one.
205
208
  const succeeded = taskSucceeded(completed)
209
+ const facts = delegationFacts(completed, description)
206
210
 
207
211
  // A schema-configured child answers with an OBJECT, and this used to
208
212
  // hand the parent model the child's prose instead — so a supervisor
@@ -240,6 +244,7 @@ export function buildAgentTool(opts: AgentToolOptions): ToolDefinition {
240
244
  return {
241
245
  success: false,
242
246
  output: '',
247
+ facts,
243
248
  error: `Subagent ${agentId} ${failureLabel(completed)}: ${detail}${recordLine ? `\n${recordLine}` : ''}`,
244
249
  data: {
245
250
  task_id: handle.taskId,
@@ -260,6 +265,7 @@ export function buildAgentTool(opts: AgentToolOptions): ToolDefinition {
260
265
  // the result programmatically.
261
266
  return {
262
267
  success: true,
268
+ facts,
263
269
  output: `${wrapUntrusted(
264
270
  {
265
271
  kind: 'agent-result',
@@ -17,6 +17,7 @@ import { defineTool } from '../defineTool.js'
17
17
  import { wrapUntrusted } from '../untrusted-envelope.js'
18
18
  import { buildAskUserQuestionTool } from './ask-user-question.js'
19
19
  import { failureLabel, taskSucceeded } from './outcome.js'
20
+ import { delegationFacts, delegationProgress } from './progress.js'
20
21
  export { ASK_USER_QUESTION_TOOL_NAME } from './ask-user-question.js'
21
22
  import { resolvePlanDependencies } from './plan-dependencies.js'
22
23
  import { describeWaitTimeout, waitForTaskWithBounds } from './wait-with-idle-bound.js'
@@ -537,6 +538,7 @@ export function buildCoordinatorTools(opts: CoordinatorToolsOptions): ToolDefini
537
538
 
538
539
  const createTask = defineTool({
539
540
  name: 'create_task',
541
+ presentCall: ({ description }) => ({ kind: 'generic', label: description.slice(0, 240) }),
540
542
  description: `Launch a task on a specialized agent.${backgroundClause} Available agents: ${agentIds.join(', ')}. Prefer compact assignments; for large context, write/read shared workspace files and pass filenames or references. To launch multiple tasks in parallel, call this tool multiple times in a single assistant turn — the runtime executes every tool_use block from one response concurrently and delivers all tool_results together, so 'fan out 8 specialists' is one assistant message with 8 create_task blocks. Do not race: until a worker's result reaches you, you know nothing about it — never fabricate, summarise or predict what it will say, in any form.`,
541
543
  inputSchema: z.object({
542
544
  agent_id: agentIdEnum.describe('Which agent to run'),
@@ -665,6 +667,7 @@ export function buildCoordinatorTools(opts: CoordinatorToolsOptions): ToolDefini
665
667
  agentId: agent_id,
666
668
  prompt,
667
669
  workingDirectory: cwd,
670
+ onEvent: delegationProgress(_context),
668
671
  runtimeContext: opts.runtimeContext,
669
672
  ...(planStepId ? { planStepId } : {}),
670
673
  ...(planId ? { planId } : {}),
@@ -782,6 +785,7 @@ export function buildCoordinatorTools(opts: CoordinatorToolsOptions): ToolDefini
782
785
  // lets `wait_for_task` and `agent_task_list` reach the output.
783
786
  return {
784
787
  success: true,
788
+ facts: delegationFacts(handle, description),
785
789
  output: `Launched ${agent_id} in the background as task ${handle.taskId}. You are not waiting on it: keep working, and its result will arrive as a task notification. To fetch it yourself, call wait_for_task with this task_id.`,
786
790
  data: {
787
791
  task_id: handle.taskId,
@@ -814,6 +818,7 @@ export function buildCoordinatorTools(opts: CoordinatorToolsOptions): ToolDefini
814
818
  if (outcome.kind === 'timeout') {
815
819
  return {
816
820
  success: false,
821
+ facts: delegationFacts(gateway.getTask(handle.taskId) ?? handle, description),
817
822
  output: describeWaitTimeout(outcome),
818
823
  data: { task_id: handle.taskId, agent_id, timed_out: outcome.cause },
819
824
  }
@@ -850,6 +855,7 @@ export function buildCoordinatorTools(opts: CoordinatorToolsOptions): ToolDefini
850
855
 
851
856
  return {
852
857
  success,
858
+ facts: delegationFacts(completed, description),
853
859
  // Framed, because a delegated worker is the component MOST
854
860
  // likely to have consumed something nobody here wrote. It was
855
861
  // handed a task like "read these files and report", it ran
@@ -0,0 +1,40 @@
1
+ import type { TaskHandle } from '../../types/agent/scheduler.js'
2
+ import type { SessionEventListener } from '../../types/session/events.js'
3
+ import type { ToolContext } from '../../types/tool/index.js'
4
+ import type { ToolFacts } from '../../types/tool/presentation.js'
5
+
6
+ export function delegationFacts(
7
+ handle: TaskHandle,
8
+ description: string,
9
+ ): Extract<ToolFacts, { kind: 'delegate' }> {
10
+ return {
11
+ kind: 'delegate',
12
+ description: description.slice(0, 240),
13
+ childSessionId: handle.childSessionId,
14
+ childStatus:
15
+ handle.result?.status === 'cancelled'
16
+ ? 'canceled'
17
+ : handle.result?.status === 'failed'
18
+ ? 'failed'
19
+ : handle.state,
20
+ }
21
+ }
22
+
23
+ export function delegationProgress(context: ToolContext): SessionEventListener {
24
+ return (event) => {
25
+ const message =
26
+ event.type === 'tool_executing'
27
+ ? `Running ${event.toolName}`
28
+ : event.type === 'agent_pending' || event.type === 'turn_started'
29
+ ? 'Starting delegated work'
30
+ : event.type === 'message_started'
31
+ ? 'Writing a reply'
32
+ : undefined
33
+ if (message) {
34
+ context.report?.(message, undefined, {
35
+ childSessionId: event.sessionId,
36
+ childStatus: 'running',
37
+ })
38
+ }
39
+ }
40
+ }
@@ -0,0 +1,97 @@
1
+ import type { ToolOutputWindow } from '../types/tool/index.js'
2
+ import { plainTerminalText } from '../utils/plain-terminal-text.js'
3
+
4
+ const MAX_LINES = 200
5
+ const MAX_BYTES = 32 * 1024
6
+
7
+ export function limitOutputLines(lines: readonly string[], omitted: number) {
8
+ const kept: string[] = []
9
+ let bytes = 0
10
+ for (let index = lines.length - 1; index >= Math.max(0, lines.length - MAX_LINES); index--) {
11
+ const line = lines[index] ?? ''
12
+ const size = Buffer.byteLength(line) + 1
13
+ if (bytes + size > MAX_BYTES) break
14
+ bytes += size
15
+ kept.push(line)
16
+ }
17
+ return { lines: kept.reverse(), omitted: omitted + lines.length - kept.length }
18
+ }
19
+
20
+ export function limitOutputWindow(output: ToolOutputWindow): ToolOutputWindow {
21
+ return {
22
+ sequence: output.sequence,
23
+ stdout: limitOutputLines(output.stdout.lines, output.stdout.omitted),
24
+ stderr: limitOutputLines(output.stderr.lines, output.stderr.omitted),
25
+ }
26
+ }
27
+
28
+ class StreamWindow {
29
+ private partial = ''
30
+ private oversized = false
31
+ private completed: { line: string; bytes: number }[] = []
32
+ private bytes = 0
33
+ private omitted = 0
34
+
35
+ append(data: string) {
36
+ let start = 0
37
+ for (let end = data.indexOf('\n'); end >= 0; end = data.indexOf('\n', start)) {
38
+ this.appendPartial(data.slice(start, end))
39
+ this.completeLine()
40
+ this.partial = ''
41
+ this.oversized = false
42
+ start = end + 1
43
+ }
44
+ this.appendPartial(data.slice(start))
45
+ }
46
+
47
+ private completeLine() {
48
+ const line = this.oversized ? '' : plainTerminalText(this.partial.replace(/\r$/, ''))
49
+ const bytes = this.oversized ? MAX_BYTES + 1 : Buffer.byteLength(line) + 1
50
+ if (bytes > MAX_BYTES) {
51
+ this.omitted += this.completed.length + 1
52
+ this.completed = []
53
+ this.bytes = 0
54
+ return
55
+ }
56
+ while (this.completed.length >= MAX_LINES || this.bytes + bytes > MAX_BYTES) {
57
+ const oldest = this.completed.shift()
58
+ if (!oldest) break
59
+ this.bytes -= oldest.bytes
60
+ this.omitted++
61
+ }
62
+ this.completed.push({ line, bytes })
63
+ this.bytes += bytes
64
+ }
65
+
66
+ private appendPartial(text: string) {
67
+ if (this.oversized) return
68
+ if (this.partial.length + text.length > MAX_BYTES) {
69
+ this.partial = ''
70
+ this.oversized = true
71
+ return
72
+ }
73
+ this.partial += text
74
+ }
75
+
76
+ snapshot(): ToolOutputWindow['stdout'] {
77
+ if (this.oversized) return { lines: [], omitted: this.omitted + this.completed.length + 1 }
78
+ const lines = this.completed.map(({ line }) => line)
79
+ const partial = plainTerminalText(this.partial)
80
+ if (partial) return limitOutputLines([...lines, partial], this.omitted)
81
+ return { lines, omitted: this.omitted }
82
+ }
83
+ }
84
+
85
+ export class ShellOutputWindow {
86
+ private streams = { stdout: new StreamWindow(), stderr: new StreamWindow() }
87
+ private sequence = 0
88
+
89
+ append(stream: 'stdout' | 'stderr', data: string): ToolOutputWindow {
90
+ this.streams[stream].append(data)
91
+ return {
92
+ sequence: ++this.sequence,
93
+ stdout: this.streams.stdout.snapshot(),
94
+ stderr: this.streams.stderr.snapshot(),
95
+ }
96
+ }
97
+ }
@@ -301,6 +301,8 @@ export type AcpSessionUpdate =
301
301
  */
302
302
  | {
303
303
  readonly kind: 'tool_call'
304
+ readonly childSessionId?: string
305
+ readonly childStatus?: import('../agent/task.js').AgentTaskState
304
306
  readonly toolCallId: string
305
307
  readonly title: string
306
308
  readonly status: 'pending' | 'completed' | 'failed'
@@ -317,6 +319,7 @@ export type AcpSessionUpdate =
317
319
  readonly progress?: {
318
320
  readonly message: string
319
321
  readonly fraction?: number
322
+ readonly output?: import('../tool/index.js').ToolOutputWindow
320
323
  }
321
324
  }
322
325
  /**
@@ -302,6 +302,8 @@ export interface BrowserValue {
302
302
  * the tool renders whichever are present.
303
303
  */
304
304
  export interface BrowserResult {
305
+ /** The preferred pane failed to open and this result came from the host's own browser. */
306
+ readonly paneFallback?: { readonly reason: string }
305
307
  /** The page after the action. */
306
308
  readonly page?: BrowserPageInfo
307
309
  /**
@@ -487,7 +487,24 @@ export interface ComputerUseOutcomeUnknown {
487
487
  // Implementations live outside @namzu/sdk (e.g. @namzu/computer-use).
488
488
  // ---------------------------------------------------------------------------
489
489
 
490
+ export type ComputerUseTimingStage =
491
+ | 'list_windows'
492
+ | 'ui_snapshot'
493
+ | 'capture_encode'
494
+ | 'input_delivery'
495
+ | 'verify_reads'
496
+ | 'settle_wait'
497
+ | 'foreground_gate'
498
+
499
+ export type ComputerUseStageTimes = Partial<Record<ComputerUseTimingStage, number>>
500
+
490
501
  export interface ComputerUseHost {
502
+ /** Collect stage durations for the asynchronous work of one tool call. */
503
+ withTiming?<T>(
504
+ record: (stage: ComputerUseTimingStage, ms: number) => void,
505
+ run: () => Promise<T>,
506
+ ): Promise<T>
507
+
491
508
  readonly id: string
492
509
  readonly capabilities: ComputerUseCapabilities
493
510