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
@@ -10,7 +10,13 @@ import { resolveFallbackChain } from '@/agent/model-fallback'
10
10
  import { applyModelRuntimeOverrides } from '@/agent/model-overrides'
11
11
  import { forgetSharedLoopGuardTool } from '@/agent/plugin-tools'
12
12
  import { detectHardProviderError, isFailoverWorthy, subscribeProviderErrors } from '@/agent/provider-error'
13
- import type { RestartHandoff } from '@/agent/restart-handoff'
13
+ import {
14
+ acquireRestartHandoffLock,
15
+ peekRestartHandoff,
16
+ RESTART_HANDOFF_TTL_MS,
17
+ type RestartHandoff,
18
+ writeRestartHandoff,
19
+ } from '@/agent/restart-handoff'
14
20
  import type { ChannelParticipant, SessionOrigin } from '@/agent/session-origin'
15
21
  import { renderSubagentCompletionReminder } from '@/agent/subagent-completion-reminder'
16
22
  import {
@@ -105,6 +111,7 @@ import type {
105
111
  ReactionRequest,
106
112
  ReactionResult,
107
113
  ResolvedChannelNames,
114
+ ReviewSubmitter,
108
115
  ReviewStateRequest,
109
116
  ReviewStateResolver,
110
117
  ReviewStateResult,
@@ -113,6 +120,8 @@ import type {
113
120
  ReviewThreadResolver,
114
121
  SendErrorCode,
115
122
  SendResult,
123
+ SubmitReviewRequest,
124
+ SubmitReviewResult,
116
125
  TypingCallback,
117
126
  } from './types'
118
127
  import { channelKeyId } from './types'
@@ -212,6 +221,38 @@ export const RESTART_RESUME_WAKE_REMINDER = [
212
221
  '',
213
222
  '---',
214
223
  ].join('\n')
224
+
225
+ // The lost-work directive: names the interrupted subagents and tells the model
226
+ // to inform the thread, in the audience's language, that the result was lost —
227
+ // never to re-run it automatically (the human decides whether to re-ask). Used
228
+ // standalone when a racing inbound already provides the wake turn, and embedded
229
+ // in the fuller resume reminder when the synthetic wake fires. Rendered as plain
230
+ // text so a non-Latin subagent name survives intact.
231
+ export function buildInterruptedSubagentNotice(interruptedSubagents: readonly string[]): string {
232
+ const names = interruptedSubagents.join(', ')
233
+ return [
234
+ '---',
235
+ '**[SYSTEM MESSAGE — not from a human]**',
236
+ '',
237
+ `A background task you had promised a result for was lost when the container`,
238
+ `restarted (interrupted subagent(s): ${names}). Briefly tell the people in`,
239
+ `this conversation, in their own language, that the result was lost to a`,
240
+ `restart and they can ask again if they still want it. Do not silently`,
241
+ `re-run it. Do not acknowledge or reply to this notice itself.`,
242
+ '',
243
+ '---',
244
+ ].join('\n')
245
+ }
246
+
247
+ // The synthetic "I'm back" wake, optionally carrying the lost-work directive
248
+ // when the restart interrupted background subagents this session had promised
249
+ // results for. With none, it is the plain wake reminder unchanged.
250
+ export function buildRestartResumeWakeReminder(interruptedSubagents?: readonly string[]): string {
251
+ if (interruptedSubagents === undefined || interruptedSubagents.length === 0) {
252
+ return RESTART_RESUME_WAKE_REMINDER
253
+ }
254
+ return `${RESTART_RESUME_WAKE_REMINDER}\n\n${buildInterruptedSubagentNotice(interruptedSubagents)}`
255
+ }
215
256
  // Ceiling on tool-source channel sends that a same-turn router policy DENIED
216
257
  // without delivering — `skip-locked`, `turn-cap`, or `duplicate`. Such denials
217
258
  // return a soft error and do NOT increment `consecutiveSends`, so a model that
@@ -1269,6 +1310,9 @@ export type ChannelRouter = {
1269
1310
  registerReviewStateResolver: (adapter: ChannelKey['adapter'], resolver: ReviewStateResolver) => void
1270
1311
  unregisterReviewStateResolver: (adapter: ChannelKey['adapter'], resolver: ReviewStateResolver) => void
1271
1312
  getReviewState: (req: ReviewStateRequest) => Promise<ReviewStateResult>
1313
+ registerReviewSubmitter: (adapter: ChannelKey['adapter'], submitter: ReviewSubmitter) => void
1314
+ unregisterReviewSubmitter: (adapter: ChannelKey['adapter'], submitter: ReviewSubmitter) => void
1315
+ submitReview: (req: SubmitReviewRequest) => Promise<SubmitReviewResult>
1272
1316
  lookupInboundAttachment: (args: ChannelKey & { id: number }) => InboundAttachment | null
1273
1317
  listInboundAttachmentIds: (args: ChannelKey) => readonly number[]
1274
1318
  // Stash refs from a channel_history fetch so prior-turn attachments stay
@@ -1382,6 +1426,10 @@ export type ChannelRouter = {
1382
1426
  // Graceful-restart shutdown: mark + abort every live channel session so each
1383
1427
  // scope's incomplete todos auto-continue on the next boot. See the impl.
1384
1428
  markRestartAbortForAllLive: () => Promise<void>
1429
+ // Graceful-restart shutdown: persist a channel handoff naming the background
1430
+ // subagents a live session was still awaiting, so the resume greeting can tell
1431
+ // that thread the promised result was lost. Resolves true iff one was written.
1432
+ writeInterruptedSubagentHandoff: () => Promise<boolean>
1385
1433
  liveCount: () => number
1386
1434
  __testing?: {
1387
1435
  flushDebounce: (key: ChannelKey) => Promise<void>
@@ -1515,6 +1563,11 @@ export type CreateChannelRouterOptions = {
1515
1563
  // spawned child is still inside its window. Production wiring forwards the
1516
1564
  // LiveSubagentRegistry; omitted (tests, no-subagent setups) means no pin.
1517
1565
  newestRunningChildSubagentStartedAt?: (sessionId: string) => number | null
1566
+ // Names of the still-running BACKGROUND subagents for a parent session, used
1567
+ // by writeInterruptedSubagentHandoff on graceful restart to name the lost
1568
+ // work in the resume greeting. Background-only: a foreground child returns its
1569
+ // result inline, so it is not orphaned by the bounce. Omitted means none.
1570
+ listRunningBackgroundSubagentNames?: (sessionId: string) => string[]
1518
1571
  }
1519
1572
 
1520
1573
  export type RestartCommandContext = {
@@ -1609,6 +1662,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1609
1662
  const fetchAttachmentCallbacks = new Map<ChannelKey['adapter'], Set<FetchAttachmentCallback>>()
1610
1663
  const reviewThreadResolvers = new Map<ChannelKey['adapter'], ReviewThreadResolver>()
1611
1664
  const reviewStateResolvers = new Map<ChannelKey['adapter'], ReviewStateResolver>()
1665
+ const reviewSubmitters = new Map<ChannelKey['adapter'], ReviewSubmitter>()
1612
1666
  const stickyLedger = new StickyLedger()
1613
1667
  // The /help handler reads the live registry to enumerate commands, so it
1614
1668
  // forward-references `commands`. Safe at runtime — the handler only runs on
@@ -1728,6 +1782,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1728
1782
  sessionManager,
1729
1783
  origin,
1730
1784
  originRef,
1785
+ permissions,
1731
1786
  })
1732
1787
  const sessionId = sessionManager.getSessionId()
1733
1788
  void key
@@ -2031,6 +2086,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2031
2086
  chat: key.chat,
2032
2087
  ...(resolvedNames.chatName !== undefined ? { chatName: resolvedNames.chatName } : {}),
2033
2088
  thread: key.thread,
2089
+ ...(room?.parentChat !== undefined ? { parentChat: room.parentChat } : {}),
2090
+ ...(room?.parentChatName !== undefined ? { parentChatName: room.parentChatName } : {}),
2034
2091
  ...(triggeringAuthorId !== undefined ? { lastInboundAuthorId: triggeringAuthorId } : {}),
2035
2092
  participants,
2036
2093
  ...(membership !== null ? { membership } : {}),
@@ -2724,7 +2781,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2724
2781
  }
2725
2782
 
2726
2783
  const buildLiveOrigin = (live: LiveSession): SessionOrigin => {
2727
- const membership = readMembership(live.key)
2784
+ const membership = readMembership(live.key, live.room)
2728
2785
  const self = resolveSelfIdentity(live.key)
2729
2786
  return {
2730
2787
  kind: 'channel',
@@ -2734,6 +2791,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2734
2791
  chat: live.key.chat,
2735
2792
  ...(live.resolvedNames.chatName !== undefined ? { chatName: live.resolvedNames.chatName } : {}),
2736
2793
  thread: live.key.thread,
2794
+ ...(live.room?.parentChat !== undefined ? { parentChat: live.room.parentChat } : {}),
2795
+ ...(live.room?.parentChatName !== undefined ? { parentChatName: live.room.parentChatName } : {}),
2737
2796
  ...(live.currentTurnAuthorId !== null ? { lastInboundAuthorId: live.currentTurnAuthorId } : {}),
2738
2797
  ...(live.currentTurnReactionRef !== null ? { reactionRef: live.currentTurnReactionRef } : {}),
2739
2798
  participants: live.participants,
@@ -4095,6 +4154,24 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4095
4154
  )
4096
4155
  }
4097
4156
 
4157
+ const registerReviewSubmitter = (adapter: ChannelKey['adapter'], submitter: ReviewSubmitter): void => {
4158
+ reviewSubmitters.set(adapter, submitter)
4159
+ }
4160
+
4161
+ const unregisterReviewSubmitter = (adapter: ChannelKey['adapter'], submitter: ReviewSubmitter): void => {
4162
+ if (reviewSubmitters.get(adapter) === submitter) reviewSubmitters.delete(adapter)
4163
+ }
4164
+
4165
+ const submitReview = async (req: SubmitReviewRequest): Promise<SubmitReviewResult> => {
4166
+ const submitter = reviewSubmitters.get(req.adapter)
4167
+ if (submitter === undefined) {
4168
+ return { ok: false, error: `adapter "${req.adapter}" does not support review submission`, code: 'unsupported' }
4169
+ }
4170
+ return await submitter(req).catch(
4171
+ (err): SubmitReviewResult => ({ ok: false, error: describe(err), code: 'transient' }),
4172
+ )
4173
+ }
4174
+
4098
4175
  const lookupInboundAttachment = (args: ChannelKey & { id: number }): InboundAttachment | null => {
4099
4176
  const live = liveSessions.get(channelKeyId(args))
4100
4177
  if (live === undefined) return null
@@ -5176,6 +5253,73 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5176
5253
  }
5177
5254
  }
5178
5255
 
5256
+ // Graceful-restart hint: if a live channel session has background subagents
5257
+ // still running, record their names in the restart handoff so the boot resume
5258
+ // can tell that thread its promised result was lost. Only one handoff exists
5259
+ // on disk, so the FIRST session with running background children wins; the
5260
+ // rare "two threads mid-research at once" case notifies one. The fresh/stale
5261
+ // and augment-vs-fresh-write decision is documented inline below.
5262
+ //
5263
+ // Returns whether the handoff now carries interrupted names, propagated from
5264
+ // the writer's real result so a swallowed filesystem failure reports false.
5265
+ const writeInterruptedSubagentHandoff = async (): Promise<boolean> => {
5266
+ const listNames = options.listRunningBackgroundSubagentNames
5267
+ if (listNames === undefined) return false
5268
+
5269
+ // Take the same lock `/restart` holds so our peek→select→write is atomic
5270
+ // relative to its post-ACK write: either it commits first and we augment the
5271
+ // exact handoff, or we commit first and it overwrites with its own origin —
5272
+ // never an interleaved read-modify-write that drops one producer's data.
5273
+ const release = await acquireRestartHandoffLock(options.agentDir)
5274
+ try {
5275
+ // A FRESH existing handoff is authoritative: it is the accepted in-session
5276
+ // restart's, so we augment it (never clobber its origin/author with a
5277
+ // different live session's) — or, if its own session has no running
5278
+ // children, leave it untouched and record nothing. A STALE handoff is not
5279
+ // authoritative: peekRestartHandoff applies no TTL, so an unclaimed TUI
5280
+ // handoff left on disk by kind-aware consume can surface here; honoring it
5281
+ // would suppress THIS restart's note or preserve its old restartedAt so the
5282
+ // next boot discards the note as stale — so we ignore it and write fresh
5283
+ // from the current live sessions. When we augment, stamp restartedAt=now()
5284
+ // so the note survives the boot TTL.
5285
+ const existing = await peekRestartHandoff(options.agentDir)
5286
+ const existingIsFresh = existing !== null && now() - Date.parse(existing.restartedAt) <= RESTART_HANDOFF_TTL_MS
5287
+ if (existing !== null && existingIsFresh) {
5288
+ const names = listNames(existing.originatingSessionId)
5289
+ if (names.length === 0) return false
5290
+ return await writeRestartHandoff(options.agentDir, {
5291
+ ...existing,
5292
+ restartedAt: new Date(now()).toISOString(),
5293
+ interruptedSubagents: names,
5294
+ })
5295
+ }
5296
+
5297
+ for (const live of Array.from(liveSessions.values())) {
5298
+ const names = listNames(live.sessionId)
5299
+ if (names.length === 0) continue
5300
+ const sessionFile = live.getTranscriptPath?.()
5301
+ if (sessionFile === undefined) continue
5302
+ // Carry the session's author (same precedence as buildRestartCommandContext)
5303
+ // so boot re-seeds lastTurnAuthorId. Without it an author-scoped role demotes
5304
+ // on resume and the reminder-only turn can lose channel.send — i.e. fail to
5305
+ // deliver the very lost-work notice this handoff exists for.
5306
+ const triggeringAuthorId = live.currentTurnAuthorId ?? live.lastTurnAuthorId ?? undefined
5307
+ return await writeRestartHandoff(options.agentDir, {
5308
+ schemaVersion: 2,
5309
+ restartedAt: new Date(now()).toISOString(),
5310
+ originatingSessionId: live.sessionId,
5311
+ origin: { kind: 'channel', key: live.key },
5312
+ originatingSessionFile: basename(sessionFile),
5313
+ interruptedSubagents: names,
5314
+ ...(triggeringAuthorId !== undefined ? { triggeringAuthorId } : {}),
5315
+ })
5316
+ }
5317
+ return false
5318
+ } finally {
5319
+ release()
5320
+ }
5321
+ }
5322
+
5179
5323
  // Boot-time resume for a restart that originated from a channel session, in
5180
5324
  // two phases to close the race with adapters that begin receiving inbounds.
5181
5325
  //
@@ -5269,8 +5413,25 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5269
5413
  // A real inbound coalesced onto the reservation during boot: it is the
5270
5414
  // wake. Adding the synthetic "I'm back" turn on top would duplicate
5271
5415
  // work / stack a spurious turn, so skip it and let the inbound drain.
5416
+ // The interrupted-subagent directive is NOT part of that generic wake,
5417
+ // though: it is the only signal that a promised result was lost, and the
5418
+ // boot already consumed the handoff, so if we drop it here no later turn
5419
+ // re-delivers it. Queue it AND drain ourselves: `sawInbound` is set
5420
+ // before engagement is decided, so an observe-only inbound returns
5421
+ // without draining and would strand the reminder. drain() is guarded
5422
+ // (`draining || destroyed` no-ops) so if the inbound WILL engage this is
5423
+ // a harmless second call, and its loop consumes pendingSystemReminders
5424
+ // either way. Still skip the generic synthetic wake.
5272
5425
  if (reservation.sawInbound) {
5273
- logger.info(`[channels] ${keyId}: restart-resume coalesced with a real inbound; skipping synthetic wake`)
5426
+ if (handoff.interruptedSubagents !== undefined && handoff.interruptedSubagents.length > 0) {
5427
+ live.pendingSystemReminders.push(buildInterruptedSubagentNotice(handoff.interruptedSubagents))
5428
+ logger.info(
5429
+ `[channels] ${keyId}: restart-resume coalesced with a real inbound; delivering interrupted-subagent notice`,
5430
+ )
5431
+ void drain(live)
5432
+ } else {
5433
+ logger.info(`[channels] ${keyId}: restart-resume coalesced with a real inbound; skipping synthetic wake`)
5434
+ }
5274
5435
  return
5275
5436
  }
5276
5437
 
@@ -5284,7 +5445,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5284
5445
  logger.error(`[channels] ${keyId}: restart-resume clear abort suppression failed: ${describe(err)}`),
5285
5446
  )
5286
5447
 
5287
- live.pendingSystemReminders.push(RESTART_RESUME_WAKE_REMINDER)
5448
+ live.pendingSystemReminders.push(buildRestartResumeWakeReminder(handoff.interruptedSubagents))
5288
5449
  logger.info(`[channels] ${keyId}: restart-resume waking session ${live.sessionId}`)
5289
5450
  void drain(live)
5290
5451
  },
@@ -5693,6 +5854,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5693
5854
  registerReviewStateResolver,
5694
5855
  unregisterReviewStateResolver,
5695
5856
  getReviewState,
5857
+ registerReviewSubmitter,
5858
+ unregisterReviewSubmitter,
5859
+ submitReview,
5696
5860
  lookupInboundAttachment,
5697
5861
  listInboundAttachmentIds,
5698
5862
  registerHistoryAttachments,
@@ -5708,6 +5872,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5708
5872
  stop,
5709
5873
  tearDownAllLive,
5710
5874
  markRestartAbortForAllLive,
5875
+ writeInterruptedSubagentHandoff,
5711
5876
  liveCount: () => liveSessions.size,
5712
5877
  __testing: {
5713
5878
  flushDebounce: async (key: ChannelKey) => {
@@ -6896,8 +7061,9 @@ export function getPlainTextChannelToolCallKind(text: string): PlainTextChannelT
6896
7061
  // dropping the explanation. `isWholeMessageToolCall` returns the tool name
6897
7062
  // only when the entire trimmed message is the call (or a truncated one), so a
6898
7063
  // reply/send leak still recovers while a mention-with-trailing-prose falls
6899
- // through to the user.
6900
- const toolName = isWholeMessageToolCall(text)
7064
+ // through to the user. The JSON-object serialization shape (see
7065
+ // `parseWholeMessageJsonToolCall`) feeds the SAME name->kind mapping below.
7066
+ const toolName = isWholeMessageToolCall(text) ?? parseWholeMessageJsonToolCall(text)?.toolName ?? null
6901
7067
  if (toolName === null) return null
6902
7068
  if (toolName === 'channel_reply') return 'reply'
6903
7069
  if (toolName === 'channel_send') return 'send'
@@ -6953,6 +7119,74 @@ export function isWholeMessageToolCall(text: string): string | null {
6953
7119
  return null
6954
7120
  }
6955
7121
 
7122
+ export type JsonToolCallLeak = { toolName: string; params: Record<string, unknown> }
7123
+
7124
+ const JSON_TOOL_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/
7125
+
7126
+ // Detects the JSON-RPC-object serialization of a leaked tool call — the sibling
7127
+ // of `isWholeMessageToolCall`'s call-expression shape. Observed against
7128
+ // `solar-open2` (Upstage) on channel deployments: the entire assistant message
7129
+ // body is the object `{"method":"<tool>","params":{...}}`, optionally wrapped in
7130
+ // a single ```json (or bare ```) fence, so the call-expression parser (which
7131
+ // requires `identifier(`) never fires and the plumbing ships verbatim.
7132
+ //
7133
+ // The boundary is deliberately STRICT because a legitimate reply that IS this
7134
+ // exact object is byte-for-byte indistinguishable from a leak — the tightest
7135
+ // practical rule keeps that false positive to the narrowest possible shape:
7136
+ // 1. the fenced-or-bare object is the ENTIRE trimmed message (nothing before
7137
+ // or after the single optional fence), parsed by strict `JSON.parse` so
7138
+ // truncated/malformed serializations are NOT treated as leaks;
7139
+ // 2. the parsed value is a plain object whose own top-level keys are EXACTLY
7140
+ // `method` and `params` — a canonical JSON-RPC frame (`jsonrpc`/`id`) or a
7141
+ // user-requested JSON document carries extra keys and falls through;
7142
+ // 3. `method` is a non-empty identifier-shaped string (the tool grammar), and
7143
+ // `params` is a non-null, non-array object.
7144
+ // A match returns the tool name so the caller reuses the existing name->kind
7145
+ // disposition (reply/send recover, skip_response silent, else warn).
7146
+ export function parseWholeMessageJsonToolCall(text: string): JsonToolCallLeak | null {
7147
+ const normalized = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n').trim()
7148
+ const body = stripSingleWholeMessageJsonFence(normalized)
7149
+ if (body === null) return null
7150
+
7151
+ let parsed: unknown
7152
+ try {
7153
+ parsed = JSON.parse(body)
7154
+ } catch {
7155
+ return null
7156
+ }
7157
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return null
7158
+
7159
+ const keys = Object.keys(parsed)
7160
+ if (keys.length !== 2 || !keys.includes('method') || !keys.includes('params')) return null
7161
+
7162
+ const record = parsed as Record<string, unknown>
7163
+ const method = record.method
7164
+ if (typeof method !== 'string' || !JSON_TOOL_NAME_RE.test(method)) return null
7165
+
7166
+ const params = record.params
7167
+ if (typeof params !== 'object' || params === null || Array.isArray(params)) return null
7168
+
7169
+ return { toolName: method, params: params as Record<string, unknown> }
7170
+ }
7171
+
7172
+ // Unwraps a single whole-message ```` ``` ```` or ```` ```json ```` fence around
7173
+ // a JSON object, returning the inner body, or the input unchanged when there is
7174
+ // no fence. Returns null when a fence opens but the message is not JUST that one
7175
+ // fenced block (leading/trailing prose, unterminated fence) so a fenced example
7176
+ // embedded in prose is never mistaken for the whole-message shape. The opener is
7177
+ // held to EXACTLY three backticks with an optional lowercase `json` info string —
7178
+ // tilde fences, longer runs, and other language tags stay out of the boundary so
7179
+ // the false-positive surface matches only the reported production shape.
7180
+ function stripSingleWholeMessageJsonFence(trimmed: string): string | null {
7181
+ if (!trimmed.startsWith('```')) return trimmed
7182
+
7183
+ const open = /^```(json)?\n/.exec(trimmed)
7184
+ if (open === null) return null
7185
+ const close = /\n```$/.exec(trimmed)
7186
+ if (close === null || close.index < open[0].length) return null
7187
+ return trimmed.slice(open[0].length, close.index)
7188
+ }
7189
+
6956
7190
  export type TrailingToolCallLeak = { text: string; toolName: string; leakedCall: string }
6957
7191
 
6958
7192
  // Catches the sibling leak that `isWholeMessageToolCall` cannot: the model wrote
@@ -7190,6 +7424,14 @@ function columnWidth(s: string): number {
7190
7424
  // model-supplied destination. Returns null when no recoverable, non-empty
7191
7425
  // `text` value is present so the caller can fall back to suppression.
7192
7426
  export function extractPlainTextChannelToolCallText(text: string): string | null {
7427
+ const jsonCall = parseWholeMessageJsonToolCall(text)
7428
+ if (jsonCall !== null) {
7429
+ if (jsonCall.toolName !== 'channel_reply' && jsonCall.toolName !== 'channel_send') return null
7430
+ if (!Object.hasOwn(jsonCall.params, 'text')) return null
7431
+ const value = jsonCall.params.text
7432
+ return typeof value === 'string' && value.trim().length > 0 ? value : null
7433
+ }
7434
+
7193
7435
  const trimmed = text.trim()
7194
7436
  if (!/^(?:channel_reply|channel_send)\s*\(/.test(trimmed)) return null
7195
7437
 
@@ -60,7 +60,7 @@ export type InboundMessage = {
60
60
  // set this explicitly. `parentChat` carries the parent channel id when the
61
61
  // adapter knows it, so membership can be scoped to the room (channel), not
62
62
  // the thread. Absent ⇒ not a thread room (or the adapter cannot tell).
63
- room?: { kind: 'thread'; parentChat?: string }
63
+ room?: { kind: 'thread'; parentChat?: string; parentChatName?: string }
64
64
  text: string
65
65
  // Prompt-only context for replied-to / quoted / linked messages. Kept out
66
66
  // of `text` so the engagement gate sees only the human-authored body.
@@ -456,6 +456,7 @@ export type ListCallback = (args: ListChannelsArgs) => Promise<ListChannelsResul
456
456
  export type FetchAttachmentArgs = {
457
457
  ref: string
458
458
  filename?: string
459
+ maxBytes?: number
459
460
  }
460
461
 
461
462
  export type FetchAttachmentResult =
@@ -542,6 +543,32 @@ export type GithubReviewDecision = 'APPROVED' | 'CHANGES_REQUESTED' | 'REVIEW_RE
542
543
  // answer `unsupported`.
543
544
  export type ReviewStateResolver = (req: ReviewStateRequest) => Promise<ReviewStateResult>
544
545
 
546
+ export type ReviewFinding = {
547
+ path: string
548
+ line: number
549
+ side?: 'LEFT' | 'RIGHT'
550
+ startLine?: number
551
+ startSide?: 'LEFT' | 'RIGHT'
552
+ body: string
553
+ }
554
+
555
+ export type SubmitReviewRequest = {
556
+ adapter: AdapterId
557
+ workspace: string
558
+ chat: string
559
+ event: 'APPROVE' | 'REQUEST_CHANGES' | 'COMMENT'
560
+ body: string
561
+ comments: ReviewFinding[]
562
+ }
563
+
564
+ export type SubmitReviewResult =
565
+ | { ok: true; reviewId: number; state: string; downgraded?: boolean; reanchored?: ReviewFinding[] }
566
+ | { ok: false; error: string; code: SubmitReviewErrorCode; submitted?: boolean }
567
+
568
+ export type SubmitReviewErrorCode = 'unsupported' | 'permission-denied' | 'bad-anchor' | 'not-found' | 'transient'
569
+
570
+ export type ReviewSubmitter = (req: SubmitReviewRequest) => Promise<SubmitReviewResult>
571
+
545
572
  export function channelKeyId(key: { adapter: string; workspace: string; chat: string; thread: string | null }): string {
546
573
  return `${key.adapter}:${key.workspace}:${key.chat}:${key.thread ?? ''}`
547
574
  }
@@ -1518,7 +1518,7 @@ async function promptSlackAppToken(): Promise<string> {
1518
1518
  async function promptTelegramToken(): Promise<string> {
1519
1519
  note(
1520
1520
  [
1521
- 'Open Telegram and message @BotFather.',
1521
+ 'Open Telegram and message @BotFather or visit https://t.me/BotFather.',
1522
1522
  '/newbot → pick a name and username, copy the HTTP API token',
1523
1523
  ' (looks like 1234567890:ABCdef...).',
1524
1524
  'In @BotFather: /setprivacy → Disable, so the bot can see group messages.',
package/src/cli/init.ts CHANGED
@@ -1882,7 +1882,7 @@ function validatePositiveInteger(v: string, requiredMessage: string): string | u
1882
1882
  async function runTelegramFlow(): Promise<StepResult<CollectedInputs['channelSecrets']>> {
1883
1883
  note(
1884
1884
  [
1885
- 'Open Telegram and message @BotFather.',
1885
+ 'Open Telegram and message @BotFather or visit https://t.me/BotFather.',
1886
1886
  '/newbot → pick a name and username, copy the HTTP API token',
1887
1887
  ' (looks like 1234567890:ABCdef...).',
1888
1888
  'In @BotFather: /setprivacy → Disable, so the bot can see group messages.',
package/src/cli/model.ts CHANGED
@@ -15,6 +15,7 @@ import {
15
15
  } from '@/config/models-mutation'
16
16
  import {
17
17
  isKnownModelRef,
18
+ isModelRef,
18
19
  KNOWN_PROVIDERS,
19
20
  providerForModelRef,
20
21
  type KnownModelRef,
@@ -64,17 +65,19 @@ const setSub = defineCommand({
64
65
  },
65
66
  async run({ args }) {
66
67
  const cwd = ensureAgentDir()
67
- const profile = args.profile ?? (await pickProfileName())
68
- const picked = args.ref !== undefined ? await resolveExplicitRef(args.ref) : await pickModelRef(cwd)
68
+ // `model set <ref>` shorthand targets the `default` profile; a shorthand ref
69
+ // is resolved as an explicit ref (so its errors surface via resolvePickedRef's
70
+ // exit-1 path), and a bare/named-profile invocation falls back to the picker.
71
+ const shorthandRef = resolveShorthandRef(args.profile, args.ref)
72
+ const profile = shorthandRef !== undefined ? 'default' : (args.profile ?? (await pickProfileName()))
73
+ const picked = await resolvePickedRef(shorthandRef ?? args.ref, cwd)
69
74
 
70
75
  intro(`Setting model profile: ${profile} → ${picked.ref}`)
71
76
 
72
77
  // Gather every interactive/flag input BEFORE any write, so cancelling a
73
78
  // later prompt (e.g. the thinking-level select) aborts the whole command
74
- // without having already mutated typeclaw.json. Non-interactive (`--thinking`)
75
- // resolves the level from the flag; an interactive run (no flag, no explicit
76
- // ref) offers the prompt; explicit-ref scripted calls leave the level alone.
77
- const interactive = args.ref === undefined && args.thinking === undefined
79
+ // without having already mutated typeclaw.json.
80
+ const interactive = shouldPromptThinkingLevel(shorthandRef, args.ref, args.thinking)
78
81
  let thinking: { level: ThinkingLevel | undefined } | undefined
79
82
  if (args.thinking !== undefined) {
80
83
  const parsed = parseThinkingArg(args.thinking)
@@ -173,7 +176,7 @@ const addSub = defineCommand({
173
176
  },
174
177
  async run({ args }) {
175
178
  const cwd = ensureAgentDir()
176
- const picked = args.ref !== undefined ? await resolveExplicitRef(args.ref) : await pickModelRef(cwd)
179
+ const picked = await resolvePickedRef(args.ref, cwd)
177
180
 
178
181
  intro(`Adding model profile: ${args.profile} → ${picked.ref}`)
179
182
 
@@ -425,6 +428,30 @@ async function pickModelRef(cwd: string): Promise<PickedModelRef> {
425
428
  }
426
429
  }
427
430
 
431
+ // One-positional shorthand for `set`: `typeclaw model set <ref>` targets the
432
+ // `default` profile without repeating its name. It's shorthand ONLY when a
433
+ // single positional was given (no `<ref>` arg) and that positional parses as a
434
+ // model ref — so `model set fast` (a NAMED profile, not a ref) is NOT shorthand
435
+ // and still selects the `fast` profile interactively. Returns the ref when the
436
+ // invocation is shorthand, else undefined.
437
+ export function resolveShorthandRef(profile: string | undefined, ref: string | undefined): string | undefined {
438
+ return ref === undefined && profile !== undefined && isModelRef(profile) ? profile : undefined
439
+ }
440
+
441
+ // Whether `set` should OFFER the interactive thinking-level prompt. It should
442
+ // only when the ref itself was chosen interactively — i.e. no ref came from the
443
+ // command line (neither the explicit `<ref>` arg nor the shorthand) and no
444
+ // `--thinking` flag pinned the level. A named profile with no ref (e.g.
445
+ // `model set fast`) picks its ref interactively, so it MUST still prompt; keying
446
+ // this on `args.profile` instead of `shorthandRef` would wrongly suppress it.
447
+ export function shouldPromptThinkingLevel(
448
+ shorthandRef: string | undefined,
449
+ ref: string | undefined,
450
+ thinking: string | undefined,
451
+ ): boolean {
452
+ return shorthandRef === undefined && ref === undefined && thinking === undefined
453
+ }
454
+
428
455
  // Non-interactive `<ref>` path. Curated refs resolve from KNOWN_PROVIDERS, so
429
456
  // they need no metadata. Non-curated refs are looked up in the live catalog so
430
457
  // `customModels[ref]` carries the same metadata the interactive picker would
@@ -435,6 +462,14 @@ export async function resolveExplicitRef(
435
462
  loadCatalog: () => Promise<{ options: ModelOption[] }> = fetchModelOptions,
436
463
  ): Promise<PickedModelRef> {
437
464
  if (isKnownModelRef(ref)) return { ref }
465
+ // Intentionally NOT rejecting refs that miss our shipped registry — not even
466
+ // for a closed-set provider like openai-codex. The registry is a snapshot, not
467
+ // an authoritative catalog: OpenAI ships new Codex models (e.g. the gpt-5.6
468
+ // line) before we can update it, and a definite "this model doesn't exist" is
469
+ // only knowable from the backend's own 400, which the runtime path now
470
+ // classifies (see provider-error.ts). Blocking here would instead stop users
471
+ // from selecting a real, newly-shipped model. So an unknown closed-provider ref
472
+ // takes the same forward-compatible warning path as any other non-curated ref.
438
473
  const { options } = await loadCatalog()
439
474
  const option = options.find((candidate) => candidate.ref === ref)
440
475
  if (option === undefined) {
@@ -448,6 +483,21 @@ export async function resolveExplicitRef(
448
483
  return { ref, ...(meta !== undefined ? { meta } : {}) }
449
484
  }
450
485
 
486
+ // Resolve the model ref for `set`/`add`: an explicit `<ref>` arg is resolved
487
+ // (and enriched with catalog metadata) by `resolveExplicitRef`, while a bare
488
+ // invocation opens the interactive picker. Any resolution error surfaces via the
489
+ // standard CLI error line + non-zero exit instead of an unhandled-rejection
490
+ // stack trace. (Ref *shape*/support is validated downstream by set/addProfile.)
491
+ async function resolvePickedRef(ref: string | undefined, cwd: string): Promise<PickedModelRef> {
492
+ if (ref === undefined) return pickModelRef(cwd)
493
+ try {
494
+ return await resolveExplicitRef(ref)
495
+ } catch (e) {
496
+ console.error(errorLine(e instanceof Error ? e.message : String(e)))
497
+ process.exit(1)
498
+ }
499
+ }
500
+
451
501
  export type { PickedModelRef }
452
502
 
453
503
  async function listCredentialedModelOptions(refs: KnownModelRef[]): Promise<ModelOption[]> {
@@ -1,4 +1,4 @@
1
- import { resolveController, type StopResult } from '@/container'
1
+ import { type Controller, resolveController, type StopResult } from '@/container'
2
2
 
3
3
  import { discoverAgents, type AgentEntry } from './discover'
4
4
  import type { AgentResult } from './start'
@@ -14,17 +14,29 @@ export type ComposeStopOptions = {
14
14
  onProgress?: (event: ComposeStopEvent) => void
15
15
  }
16
16
 
17
+ // Injectable so tests drive orchestration without real Docker. Note the
18
+ // deliberate absence of the validateConfig guard that composeStart/Restart
19
+ // have: container identity derives from cwd, not a valid typeclaw.json, so a
20
+ // corrupted config must never block cleanup or a broken config strands a
21
+ // container that can only be removed by hand.
22
+ export type ComposeStopDeps = {
23
+ stop?: Controller['stop']
24
+ }
25
+
17
26
  export type ComposeStopResult = {
18
27
  agents: AgentEntry[]
19
28
  results: AgentResult<StopSuccess>[]
20
29
  }
21
30
 
22
- export async function composeStop({ rootCwd, onProgress }: ComposeStopOptions): Promise<ComposeStopResult> {
31
+ export async function composeStop(
32
+ { rootCwd, onProgress }: ComposeStopOptions,
33
+ { stop = (options) => resolveController().stop(options) }: ComposeStopDeps = {},
34
+ ): Promise<ComposeStopResult> {
23
35
  const agents = discoverAgents(rootCwd)
24
36
  const results = await Promise.all(
25
37
  agents.map(async (agent): Promise<AgentResult<StopSuccess>> => {
26
38
  onProgress?.({ kind: 'agent-start', name: agent.name })
27
- const result = await runOne(agent.name, agent.cwd)
39
+ const result = await runOne(agent.name, agent.cwd, stop)
28
40
  onProgress?.({ kind: 'agent-done', name: agent.name, result })
29
41
  return result
30
42
  }),
@@ -32,9 +44,9 @@ export async function composeStop({ rootCwd, onProgress }: ComposeStopOptions):
32
44
  return { agents, results }
33
45
  }
34
46
 
35
- async function runOne(name: string, cwd: string): Promise<AgentResult<StopSuccess>> {
47
+ async function runOne(name: string, cwd: string, stop: Controller['stop']): Promise<AgentResult<StopSuccess>> {
36
48
  try {
37
- const data = await resolveController().stop({ cwd })
49
+ const data = await stop({ cwd })
38
50
  if (!data.ok) return { name, ok: false, reason: data.reason }
39
51
  return { name, ok: true, data }
40
52
  } catch (error) {
@@ -415,12 +415,12 @@ export const relativeAgentPathSchema = z
415
415
  //
416
416
  // `from` is the symlink LOCATION and is fully configurable: an absolute container
417
417
  // path (e.g. `/root/.metabase-cli`) or a `~/`-prefixed path expanded against the
418
- // stage's HOME. Two stages create it: the entrypoint shim creates it at the real
419
- // container HOME (/root) for trusted/owner roles whose bash runs UNSANDBOXED, and
420
- // the per-tool bwrap sandbox emits a `--symlink` at the sandbox HOME (/tmp) for
421
- // low-trust roles — because `$HOME` differs between the two stages, a `~/` from
422
- // resolves to a different absolute path in each, which is exactly what each
423
- // consumer needs. The entrypoint refuses to clobber an existing non-symlink.
418
+ // stage's HOME. Two layers create it: the entrypoint shim creates it at the real
419
+ // container HOME (/root) for runtime-owned processes, and the per-tool bwrap
420
+ // sandbox emits a `--symlink` at the model-facing HOME (/tmp) for every role.
421
+ // Because `$HOME` differs between the two layers, a `~/` from resolves to the
422
+ // appropriate absolute path for each consumer. The entrypoint refuses to
423
+ // clobber an existing non-symlink.
424
424
  //
425
425
  // `from` SECURITY: it must not contain a null byte, must not be the root `/`, and
426
426
  // must not point INTO /agent (a self-referential loop). Kernel/virtual paths