typeclaw 0.45.1 → 0.46.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 (142) hide show
  1. package/README.md +1 -1
  2. package/package.json +2 -1
  3. package/src/agent/git-nudge.ts +2 -1
  4. package/src/agent/index.ts +44 -30
  5. package/src/agent/live-subagents.ts +18 -0
  6. package/src/agent/multimodal/index.ts +1 -1
  7. package/src/agent/multimodal/look-at.ts +78 -44
  8. package/src/agent/multimodal/looker.ts +151 -39
  9. package/src/agent/network/response-body.ts +26 -0
  10. package/src/agent/network/safe-http.ts +198 -0
  11. package/src/agent/plugin-tools.ts +379 -157
  12. package/src/agent/provider-error.ts +52 -1
  13. package/src/agent/restart/index.ts +61 -40
  14. package/src/agent/restart-handoff/index.ts +73 -4
  15. package/src/agent/reviewer-bash-policy.ts +42 -1
  16. package/src/agent/session-origin.ts +2 -0
  17. package/src/agent/subagent-drain.ts +117 -7
  18. package/src/agent/subagents.ts +49 -16
  19. package/src/agent/throttle-circuit.ts +25 -5
  20. package/src/agent/tool-error-remediation.ts +72 -0
  21. package/src/agent/tool-file-safety.ts +1050 -0
  22. package/src/agent/tools/channel-fetch-attachment.ts +10 -3
  23. package/src/agent/tools/ddg.ts +16 -2
  24. package/src/agent/tools/post-github-review.ts +199 -0
  25. package/src/agent/tools/spawn-subagent.ts +21 -18
  26. package/src/agent/tools/webfetch/fetch.ts +143 -183
  27. package/src/agent/tools/webfetch/tool.ts +2 -3
  28. package/src/agent/tools/websearch.ts +23 -2
  29. package/src/agent/tools-without-local-file-operands.ts +27 -0
  30. package/src/agent/turn-runner.ts +86 -6
  31. package/src/bundled-plugins/backup/index.ts +2 -1
  32. package/src/bundled-plugins/backup/runner.ts +2 -1
  33. package/src/bundled-plugins/doc-render/render.ts +93 -12
  34. package/src/bundled-plugins/doc-render/skills/typeclaw-render-pdf/SKILL.md +13 -13
  35. package/src/bundled-plugins/github-cli-auth/effective-approval.ts +16 -6
  36. package/src/bundled-plugins/github-cli-auth/gh-command.ts +555 -15
  37. package/src/bundled-plugins/github-cli-auth/index.ts +131 -135
  38. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +138 -0
  39. package/src/bundled-plugins/guard/policies/uncommitted-changes.ts +2 -1
  40. package/src/bundled-plugins/memory/README.md +23 -11
  41. package/src/bundled-plugins/memory/append-tool.ts +15 -8
  42. package/src/bundled-plugins/memory/citations.ts +22 -9
  43. package/src/bundled-plugins/memory/dreaming.ts +13 -8
  44. package/src/bundled-plugins/memory/find-entry-tool.ts +4 -0
  45. package/src/bundled-plugins/memory/index.ts +0 -4
  46. package/src/bundled-plugins/memory/load-memory.ts +8 -3
  47. package/src/bundled-plugins/memory/provenance-index.ts +717 -0
  48. package/src/bundled-plugins/memory/provenance-sanitize.ts +40 -0
  49. package/src/bundled-plugins/memory/references/store-reference-tool.ts +4 -0
  50. package/src/bundled-plugins/memory/search-tool.ts +163 -60
  51. package/src/bundled-plugins/memory/stream-events.ts +2 -0
  52. package/src/bundled-plugins/memory/vector/hybrid.ts +126 -13
  53. package/src/bundled-plugins/researcher/write-report.ts +6 -3
  54. package/src/bundled-plugins/reviewer/index.ts +2 -2
  55. package/src/bundled-plugins/reviewer/reviewer.ts +10 -3
  56. package/src/bundled-plugins/reviewer/skills/code-review.ts +19 -9
  57. package/src/bundled-plugins/scout/scout.ts +8 -0
  58. package/src/bundled-plugins/security/index.ts +4 -4
  59. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +1 -0
  60. package/src/bundled-plugins/security/policies/private-surface-read.ts +220 -29
  61. package/src/bundled-plugins/security/policies/secret-exfil-read.ts +1 -0
  62. package/src/bundled-plugins/security/policies/ssrf.ts +29 -9
  63. package/src/channels/adapters/discord-bot-channel-resolver.ts +26 -14
  64. package/src/channels/adapters/discord-bot-thread-room.ts +44 -12
  65. package/src/channels/adapters/discord-bot.ts +66 -6
  66. package/src/channels/adapters/discord-channel-resolver.ts +91 -23
  67. package/src/channels/adapters/discord-id.ts +4 -0
  68. package/src/channels/adapters/discord-resolver-cache.ts +41 -0
  69. package/src/channels/adapters/discord.ts +57 -7
  70. package/src/channels/adapters/github/auth-app.ts +41 -12
  71. package/src/channels/adapters/github/index.ts +23 -11
  72. package/src/channels/adapters/github/review-submitter.ts +302 -0
  73. package/src/channels/adapters/kakaotalk-channel-resolver.ts +5 -3
  74. package/src/channels/adapters/kakaotalk-fetch-attachment.ts +8 -4
  75. package/src/channels/adapters/kakaotalk-typing.ts +17 -15
  76. package/src/channels/adapters/slack-attachment-download.ts +71 -0
  77. package/src/channels/adapters/slack-bot.ts +19 -8
  78. package/src/channels/adapters/slack-classify.ts +21 -2
  79. package/src/channels/adapters/slack.ts +59 -7
  80. package/src/channels/adapters/telegram-bot.ts +18 -5
  81. package/src/channels/adapters/webex-bot.ts +8 -3
  82. package/src/channels/adapters/webex.ts +8 -3
  83. package/src/channels/fetch-attachment.ts +43 -0
  84. package/src/{bundled-plugins/github-cli-auth/approve-idempotency.ts → channels/github-review-verdict-coordinator.ts} +25 -1
  85. package/src/channels/github-token-bridge.ts +10 -3
  86. package/src/channels/manager.ts +9 -0
  87. package/src/channels/router.ts +248 -6
  88. package/src/channels/types.ts +28 -1
  89. package/src/cli/channel.ts +1 -1
  90. package/src/cli/init.ts +1 -1
  91. package/src/cli/model.ts +57 -7
  92. package/src/compose/stop.ts +17 -5
  93. package/src/config/config.ts +6 -6
  94. package/src/config/models-mutation.ts +13 -1
  95. package/src/config/providers.ts +176 -0
  96. package/src/container/start.ts +49 -10
  97. package/src/doctor/checks.ts +3 -1
  98. package/src/doctor/commit.ts +2 -1
  99. package/src/doctor/file-ownership.ts +52 -0
  100. package/src/dreams/git.ts +2 -1
  101. package/src/git/hookless.ts +5 -0
  102. package/src/git/reconcile-ignored.ts +18 -5
  103. package/src/git/secret-history.ts +371 -0
  104. package/src/git/system-commit.ts +12 -6
  105. package/src/init/dockerfile.ts +86 -5
  106. package/src/init/index.ts +17 -5
  107. package/src/init/models-dev.ts +4 -0
  108. package/src/init/validate-api-key.ts +2 -0
  109. package/src/mcp/tools.ts +16 -3
  110. package/src/permissions/builtins.ts +3 -1
  111. package/src/plugin/context.ts +2 -0
  112. package/src/plugin/index.ts +1 -0
  113. package/src/plugin/manager.ts +4 -0
  114. package/src/plugin/types.ts +21 -0
  115. package/src/run/index.ts +40 -0
  116. package/src/run/llm-fetch-observer.ts +41 -4
  117. package/src/sandbox/build.ts +37 -15
  118. package/src/sandbox/canonical-secrets.ts +18 -0
  119. package/src/sandbox/env-exposure.ts +80 -0
  120. package/src/sandbox/errors.ts +13 -6
  121. package/src/sandbox/hidden-paths.ts +102 -44
  122. package/src/sandbox/index.ts +22 -4
  123. package/src/sandbox/package-install.ts +3 -27
  124. package/src/sandbox/policy.ts +11 -25
  125. package/src/sandbox/privileged-runtime.ts +255 -0
  126. package/src/sandbox/session-tmp.ts +8 -2
  127. package/src/sandbox/writable-zones.ts +204 -140
  128. package/src/secrets/index.ts +8 -0
  129. package/src/secrets/refresh-provider-oauth.ts +128 -0
  130. package/src/server/command-runner.ts +48 -4
  131. package/src/server/index.ts +4 -0
  132. package/src/skills/typeclaw-channel-github/SKILL.md +49 -56
  133. package/src/skills/typeclaw-claude-code/SKILL.md +24 -60
  134. package/src/skills/typeclaw-claude-code/references/auth-flow.md +17 -158
  135. package/src/skills/typeclaw-codex-cli/SKILL.md +19 -49
  136. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +17 -154
  137. package/src/skills/typeclaw-config/SKILL.md +5 -5
  138. package/src/skills/typeclaw-config/references/recommended-mounts.md +24 -24
  139. package/src/skills/typeclaw-github-contributing/SKILL.md +23 -26
  140. package/src/skills/typeclaw-memory/SKILL.md +9 -3
  141. package/src/skills/typeclaw-permissions/SKILL.md +19 -15
  142. package/typeclaw.schema.json +20 -0
@@ -1,10 +1,10 @@
1
- import { mkdir, writeFile } from 'node:fs/promises'
2
1
  import { join, sep } from 'node:path'
3
2
 
4
3
  import { Type } from '@mariozechner/pi-ai'
5
4
  import { defineTool } from '@mariozechner/pi-coding-agent'
6
5
 
7
6
  import type { SessionOrigin } from '@/agent/session-origin'
7
+ import { TOOL_INPUT_MAX_BYTES, writeFileAnchored } from '@/agent/tool-file-safety'
8
8
  import type { ChannelRouter } from '@/channels/router'
9
9
  import type { AdapterId } from '@/channels/schema'
10
10
  import type { PermissionService } from '@/permissions'
@@ -32,6 +32,7 @@ export type CreateChannelFetchAttachmentToolOptions = {
32
32
  // its follow-up look_at/read). See buildChannelTools for the decision.
33
33
  resolveBaseDir?: () => string
34
34
  logger?: ChannelToolLogger
35
+ agentDir?: string
35
36
  }
36
37
 
37
38
  // workspace/ is private-surface: readable only by roles with fs.see.private.
@@ -46,6 +47,7 @@ export function createChannelFetchAttachmentTool({
46
47
  inboxDir,
47
48
  resolveBaseDir,
48
49
  logger = consoleChannelLogger,
50
+ agentDir = process.cwd(),
49
51
  }: CreateChannelFetchAttachmentToolOptions) {
50
52
  const fallbackBaseDir = inboxDir ?? DEFAULT_INBOX_DIR
51
53
  const adapter = origin.adapter
@@ -108,6 +110,7 @@ export function createChannelFetchAttachmentTool({
108
110
  const filename = params.filename ?? found.filename
109
111
  const result = await router.fetchAttachment(adapter, {
110
112
  ref,
113
+ maxBytes: TOOL_INPUT_MAX_BYTES.channel_upload,
111
114
  ...(filename !== undefined ? { filename } : {}),
112
115
  })
113
116
  if (!result.ok) {
@@ -123,8 +126,12 @@ export function createChannelFetchAttachmentTool({
123
126
  const targetDir = join(baseDir, adapter, refSlug)
124
127
  const targetPath = join(targetDir, safeFilename)
125
128
  try {
126
- await mkdir(targetDir, { recursive: true })
127
- await writeFile(targetPath, result.buffer)
129
+ await writeFileAnchored({
130
+ targetPath,
131
+ data: result.buffer,
132
+ agentDir,
133
+ tool: 'channel_fetch_attachment',
134
+ })
128
135
  } catch (err) {
129
136
  const message = err instanceof Error ? err.message : String(err)
130
137
  logger.warn(formatChannelToolFailure('channel_fetch_attachment', `${adapter}: write failed: ${message}`))
@@ -12,7 +12,7 @@
12
12
  // TLS handshake + HTTP/2 settings + header ordering. See that file's header
13
13
  // for the full rationale and AGENTS.md §"Web search" for the original story.
14
14
 
15
- import { curlImpersonate } from './curl-impersonate'
15
+ import { CurlImpersonateError, curlImpersonate, isCurlExitTimeout } from './curl-impersonate'
16
16
  import { createKeyedSemaphore } from './keyed-semaphore'
17
17
  import { type SearchRetryOptions, withSearchRetry } from './search-retry'
18
18
 
@@ -61,12 +61,26 @@ export async function ddgSearch(query: string, limit: number, signal?: AbortSign
61
61
  }
62
62
  return parseDdgHtml(html).slice(0, limit)
63
63
  },
64
- { ...retryOverride, shouldRetry: (error) => error instanceof DdgCaptchaError, signal },
64
+ { ...retryOverride, shouldRetry: isTransientSearchError, signal },
65
65
  ),
66
66
  signal,
67
67
  )
68
68
  }
69
69
 
70
+ // Both a tripped CAPTCHA and a bare connection timeout are transient: DDG's
71
+ // gate lifts after a cooldown, and an egress timeout is almost always a
72
+ // momentary network blip (the incident that motivated this: an agent's egress
73
+ // timed out for a few minutes, then recovered). Retrying both under the bounded
74
+ // `withSearchRetry` backoff turns an otherwise-unbounded model-driven retry
75
+ // loop into at most `attempts` code-level tries that then surface a single
76
+ // terminal error. A hard network failure (DNS, refused, TLS) is NOT retried —
77
+ // it won't fix itself on a re-run and would just burn the budget.
78
+ export function isTransientSearchError(error: unknown): boolean {
79
+ if (error instanceof DdgCaptchaError) return true
80
+ if (error instanceof CurlImpersonateError && isCurlExitTimeout(error)) return true
81
+ return false
82
+ }
83
+
70
84
  export class DdgCaptchaError extends Error {
71
85
  constructor() {
72
86
  super('DuckDuckGo returned a CAPTCHA page (rate-limited). Try again later or with a different query.')
@@ -0,0 +1,199 @@
1
+ import { Type } from '@mariozechner/pi-ai'
2
+ import { defineTool } from '@mariozechner/pi-coding-agent'
3
+
4
+ import { recordReview, recordReviewOutput, type ReviewVerdict } from '@/channels/github-review-turn-ledger'
5
+ import { createSharedReviewVerdictGuard, type ReviewVerdictGuard } from '@/channels/github-review-verdict-coordinator'
6
+ import type { ChannelRouter } from '@/channels/router'
7
+ import type { ReviewFinding, SubmitReviewRequest } from '@/channels/types'
8
+
9
+ import { type ChannelToolLogger, consoleChannelLogger, formatChannelToolFailure } from './channel-log'
10
+ import { type ChannelReplyOrigin, TOOL_RESULT_PREFIX } from './channel-reply'
11
+ import { fenceToolResult } from './runtime-notice'
12
+
13
+ type PostGithubReviewDetails = {
14
+ ok: boolean
15
+ error?: string
16
+ code?: string
17
+ reviewId?: number
18
+ state?: string
19
+ downgraded?: boolean
20
+ reanchored?: ReviewFinding[]
21
+ }
22
+
23
+ export function createPostGithubReviewTool(options: {
24
+ router: ChannelRouter
25
+ origin: ChannelReplyOrigin
26
+ sessionId: string
27
+ logger?: ChannelToolLogger
28
+ verdictGuard?: ReviewVerdictGuard
29
+ }) {
30
+ const { router, origin, sessionId, logger = consoleChannelLogger } = options
31
+ const verdictGuard = options.verdictGuard ?? createSharedReviewVerdictGuard()
32
+ return defineTool({
33
+ name: 'post_github_review',
34
+ label: 'Post GitHub PR Review',
35
+ description:
36
+ 'GitHub channel sessions only. Submit a formal PR review. The adapter resolves the head SHA, validates diff anchors, moves out-of-diff findings into the body, enforces approval policy, and verifies the posted review.',
37
+ parameters: Type.Object({
38
+ event: Type.Union([Type.Literal('APPROVE'), Type.Literal('REQUEST_CHANGES'), Type.Literal('COMMENT')]),
39
+ body: Type.String({ minLength: 1 }),
40
+ comments: Type.Optional(
41
+ Type.Array(
42
+ Type.Object({
43
+ path: Type.String({ minLength: 1 }),
44
+ line: Type.Integer({ minimum: 1 }),
45
+ side: Type.Optional(Type.Union([Type.Literal('LEFT'), Type.Literal('RIGHT')])),
46
+ start_line: Type.Optional(Type.Integer({ minimum: 1 })),
47
+ start_side: Type.Optional(Type.Union([Type.Literal('LEFT'), Type.Literal('RIGHT')])),
48
+ body: Type.String({ minLength: 1 }),
49
+ }),
50
+ { minItems: 1 },
51
+ ),
52
+ ),
53
+ }),
54
+ async execute(toolCallId, params) {
55
+ if (origin.adapter !== 'github') return denied(logger, 'post_github_review is only supported on github sessions.')
56
+ const prNumber = parsePrNumber(origin.chat)
57
+ if (prNumber === null) return denied(logger, `invalid GitHub review target: ${origin.chat}`)
58
+ const verdict = decisiveVerdict(params.event)
59
+ const coordinationCallId = `${sessionId}:${toolCallId}`
60
+ if (verdict !== null) {
61
+ const blocked = await verdictGuard.guard({
62
+ callId: coordinationCallId,
63
+ workspace: origin.workspace,
64
+ prNumber,
65
+ verdict,
66
+ })
67
+ if (blocked !== null) return denied(logger, blocked.reason)
68
+ }
69
+ const request: SubmitReviewRequest = {
70
+ adapter: 'github',
71
+ workspace: origin.workspace,
72
+ chat: origin.chat,
73
+ event: params.event,
74
+ body: params.body,
75
+ comments: (params.comments ?? []).map(toReviewFinding),
76
+ }
77
+ let releaseAsLanded = false
78
+ try {
79
+ const result = await router.submitReview(request)
80
+ if (!result.ok) {
81
+ // A POST whose verification failed may already have landed. Keep the
82
+ // short conservative shield, but never credit an unverified ledger.
83
+ releaseAsLanded = verdict !== null && result.submitted === true
84
+ return denied(logger, result.error, result.code)
85
+ }
86
+
87
+ const effective = effectiveReviewState(result.state)
88
+ if (effective === null)
89
+ return denied(logger, `GitHub returned an unknown verified review state: ${result.state}`)
90
+ releaseAsLanded = verdict !== null && effective === verdict
91
+ creditVerifiedReview({ sessionId, workspace: origin.workspace, prNumber, effective })
92
+
93
+ const receipt = renderReceipt(
94
+ result.reviewId,
95
+ result.state,
96
+ result.downgraded === true,
97
+ result.reanchored ?? [],
98
+ )
99
+ const details: PostGithubReviewDetails = {
100
+ ok: true,
101
+ reviewId: result.reviewId,
102
+ state: result.state,
103
+ ...(result.downgraded === true ? { downgraded: true } : {}),
104
+ ...(result.reanchored !== undefined ? { reanchored: result.reanchored } : {}),
105
+ }
106
+ return { content: [{ type: 'text' as const, text: fenceToolResult(receipt) }], details }
107
+ } finally {
108
+ if (verdict !== null) {
109
+ await verdictGuard.release({ callId: coordinationCallId, succeeded: releaseAsLanded })
110
+ }
111
+ }
112
+ },
113
+ })
114
+ }
115
+
116
+ function parsePrNumber(chat: string): number | null {
117
+ const match = /^pr:(\d+)$/.exec(chat)
118
+ if (match?.[1] === undefined) return null
119
+ const value = Number(match[1])
120
+ return Number.isSafeInteger(value) && value > 0 ? value : null
121
+ }
122
+
123
+ function decisiveVerdict(event: SubmitReviewRequest['event']): ReviewVerdict | null {
124
+ return event === 'APPROVE' || event === 'REQUEST_CHANGES' ? event : null
125
+ }
126
+
127
+ function effectiveReviewState(state: string): ReviewVerdict | 'COMMENT' | null {
128
+ if (state === 'APPROVED') return 'APPROVE'
129
+ if (state === 'CHANGES_REQUESTED') return 'REQUEST_CHANGES'
130
+ if (state === 'COMMENTED') return 'COMMENT'
131
+ return null
132
+ }
133
+
134
+ function creditVerifiedReview(args: {
135
+ sessionId: string
136
+ workspace: string
137
+ prNumber: number
138
+ effective: ReviewVerdict | 'COMMENT'
139
+ }): void {
140
+ if (args.effective === 'COMMENT') {
141
+ recordReviewOutput({
142
+ sessionId: args.sessionId,
143
+ workspace: args.workspace,
144
+ prNumber: args.prNumber,
145
+ state: 'COMMENT',
146
+ })
147
+ return
148
+ }
149
+ // recordReview also emits the review-output observer signal for decisive
150
+ // states, keeping verdict and output credit atomic.
151
+ recordReview({
152
+ sessionId: args.sessionId,
153
+ workspace: args.workspace,
154
+ prNumber: args.prNumber,
155
+ verdict: args.effective,
156
+ })
157
+ }
158
+
159
+ function denied(logger: ChannelToolLogger, error: string, code?: string) {
160
+ logger.warn(formatChannelToolFailure('post_github_review', error))
161
+ const details: PostGithubReviewDetails = { ok: false, error, ...(code !== undefined ? { code } : {}) }
162
+ return {
163
+ content: [{ type: 'text' as const, text: `${TOOL_RESULT_PREFIX}post_github_review denied: ${error}` }],
164
+ details,
165
+ }
166
+ }
167
+
168
+ function toReviewFinding(comment: {
169
+ path: string
170
+ line: number
171
+ side?: 'LEFT' | 'RIGHT'
172
+ start_line?: number
173
+ start_side?: 'LEFT' | 'RIGHT'
174
+ body: string
175
+ }): ReviewFinding {
176
+ return {
177
+ path: comment.path,
178
+ line: comment.line,
179
+ ...(comment.side !== undefined ? { side: comment.side } : {}),
180
+ ...(comment.start_line !== undefined ? { startLine: comment.start_line } : {}),
181
+ ...(comment.start_side !== undefined ? { startSide: comment.start_side } : {}),
182
+ body: comment.body,
183
+ }
184
+ }
185
+
186
+ function renderReceipt(
187
+ reviewId: number,
188
+ state: string,
189
+ downgraded: boolean,
190
+ reanchored: readonly ReviewFinding[],
191
+ ): string {
192
+ const notes = [
193
+ downgraded ? 'APPROVE was downgraded to COMMENT by operator policy.' : null,
194
+ reanchored.length > 0
195
+ ? `${reanchored.length} out-of-diff finding(s) moved into the review body: ${reanchored.map((finding) => `${finding.path}:${finding.line}`).join(', ')}.`
196
+ : null,
197
+ ].filter((note): note is string => note !== null)
198
+ return [`GitHub review posted: id=${reviewId}, state=${state}.`, ...notes].join('\n')
199
+ }
@@ -176,24 +176,27 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
176
176
 
177
177
  void completion.then((c) => {
178
178
  const durationMs = now() - startedAt
179
- liveRegistry.recordCompletion(taskId, completionToFinalShape(c, durationMs))
180
- if (stream && background) {
181
- const hasRecoverableOutput = !c.ok && c.finalMessage !== undefined
182
- stream.publish({
183
- target: { kind: 'broadcast' },
184
- payload: {
185
- kind: 'subagent.completed',
186
- taskId,
187
- subagent: subagentName,
188
- parentSessionId,
189
- ok: c.ok,
190
- durationMs,
191
- ...(c.ok ? {} : { error: c.error }),
192
- ...(hasRecoverableOutput ? { hasRecoverableOutput: true } : {}),
193
- ...(channelKey !== undefined ? { channelKey } : {}),
194
- },
195
- })
196
- }
179
+ // First-writer-wins: if the parent drain already settled this child by
180
+ // timeout, our real completion lost — skip both the overwrite and the
181
+ // broadcast so exactly one canonical completed-event is emitted (the
182
+ // winner's).
183
+ const won = liveRegistry.recordCompletionIfRunning(taskId, completionToFinalShape(c, durationMs))
184
+ if (!won || !stream || !background) return
185
+ const hasRecoverableOutput = !c.ok && c.finalMessage !== undefined
186
+ stream.publish({
187
+ target: { kind: 'broadcast' },
188
+ payload: {
189
+ kind: 'subagent.completed',
190
+ taskId,
191
+ subagent: subagentName,
192
+ parentSessionId,
193
+ ok: c.ok,
194
+ durationMs,
195
+ ...(c.ok ? {} : { error: c.error }),
196
+ ...(hasRecoverableOutput ? { hasRecoverableOutput: true } : {}),
197
+ ...(channelKey !== undefined ? { channelKey } : {}),
198
+ },
199
+ })
197
200
  })
198
201
 
199
202
  if (background) {