typeclaw 0.51.0 → 0.52.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 (202) hide show
  1. package/dist/types/agent/bash-sandbox-env.d.ts +2 -0
  2. package/dist/types/agent/bash-sandbox.d.ts +4 -0
  3. package/dist/types/agent/index.d.ts +5 -0
  4. package/dist/types/agent/multimodal/look-at.d.ts +1 -1
  5. package/dist/types/agent/plugin-tools.d.ts +4 -0
  6. package/dist/types/agent/prompt-cache-key.d.ts +1 -0
  7. package/dist/types/agent/session-tail.d.ts +12 -0
  8. package/dist/types/agent/subagents.d.ts +5 -0
  9. package/dist/types/agent/system-prompt-composition.d.ts +1 -0
  10. package/dist/types/agent/system-prompt.d.ts +2 -0
  11. package/dist/types/agent/tools/channel-disengage.d.ts +1 -1
  12. package/dist/types/agent/tools/channel-edit.d.ts +1 -1
  13. package/dist/types/agent/tools/channel-fetch-attachment.d.ts +1 -1
  14. package/dist/types/agent/tools/channel-handoff.d.ts +1 -1
  15. package/dist/types/agent/tools/channel-history.d.ts +1 -1
  16. package/dist/types/agent/tools/channel-react.d.ts +1 -1
  17. package/dist/types/agent/tools/channel-read.d.ts +10 -2
  18. package/dist/types/agent/tools/channel-reply.d.ts +1 -1
  19. package/dist/types/agent/tools/channel-send.d.ts +1 -1
  20. package/dist/types/agent/tools/channel-session-search.d.ts +1 -1
  21. package/dist/types/agent/tools/grant-role.d.ts +1 -1
  22. package/dist/types/agent/tools/post-github-review.d.ts +1 -1
  23. package/dist/types/agent/tools/restart.d.ts +1 -1
  24. package/dist/types/agent/tools/skip-response.d.ts +1 -1
  25. package/dist/types/agent/tools/spawn-subagent.d.ts +2 -1
  26. package/dist/types/agent/tools/stream-snapshot.d.ts +1 -1
  27. package/dist/types/agent/tools/subagent-cancel.d.ts +1 -1
  28. package/dist/types/agent/tools/subagent-output.d.ts +1 -1
  29. package/dist/types/agent/tools/todo/index.d.ts +1 -1
  30. package/dist/types/agent/tools/webfetch/adaptive-html.d.ts +3 -3
  31. package/dist/types/agent/tools/webfetch/strategies/readability-process.d.ts +48 -0
  32. package/dist/types/agent/tools/webfetch/tool.d.ts +2 -2
  33. package/dist/types/agent/tools/websearch.d.ts +1 -1
  34. package/dist/types/channels/adapters/github/auth-app.d.ts +25 -0
  35. package/dist/types/channels/adapters/github/auth-pat.d.ts +17 -0
  36. package/dist/types/channels/adapters/github/auth.d.ts +24 -0
  37. package/dist/types/channels/github-token-bridge.d.ts +4 -0
  38. package/dist/types/channels/lost-background-context.d.ts +2 -0
  39. package/dist/types/channels/persistence.d.ts +1 -0
  40. package/dist/types/channels/router.d.ts +5 -1
  41. package/dist/types/channels/types.d.ts +1 -0
  42. package/dist/types/coding-agent/tool.d.ts +1 -1
  43. package/dist/types/config/config.d.ts +20 -11
  44. package/dist/types/config/providers.d.ts +47 -0
  45. package/dist/types/eval/sandbox.d.ts +2 -0
  46. package/dist/types/git/resolve-identity.d.ts +2 -0
  47. package/dist/types/init/dockerfile.d.ts +1 -0
  48. package/dist/types/init/gitignore.d.ts +1 -1
  49. package/dist/types/permissions/builtins.d.ts +1 -0
  50. package/dist/types/plugin/types.d.ts +3 -0
  51. package/dist/types/sandbox/canonical-secrets.d.ts +2 -2
  52. package/dist/types/sandbox/coding-agent.d.ts +1 -1
  53. package/dist/types/sandbox/dependency-bins.d.ts +1 -0
  54. package/dist/types/sandbox/dev-source.d.ts +2 -2
  55. package/dist/types/sandbox/hidden-paths.d.ts +1 -0
  56. package/dist/types/sandbox/index.d.ts +1 -1
  57. package/dist/types/sandbox/policy.d.ts +3 -0
  58. package/dist/types/typevault/cli-path.d.ts +2 -0
  59. package/dist/types/typevault/envelope-store.d.ts +11 -0
  60. package/dist/types/typevault/lifecycle.d.ts +13 -0
  61. package/dist/types/typevault/vault.d.ts +27 -0
  62. package/package.json +8 -7
  63. package/scripts/test.ts +252 -0
  64. package/src/agent/bash-sandbox-env.ts +33 -1
  65. package/src/agent/bash-sandbox.ts +20 -6
  66. package/src/agent/index.ts +120 -31
  67. package/src/agent/multimodal/look-at.ts +1 -1
  68. package/src/agent/plugin-tools.ts +35 -1
  69. package/src/agent/prompt-cache-key.ts +26 -3
  70. package/src/agent/session-origin.ts +39 -18
  71. package/src/agent/session-tail.ts +28 -0
  72. package/src/agent/subagents.ts +21 -2
  73. package/src/agent/system-prompt-composition.ts +18 -0
  74. package/src/agent/system-prompt.ts +39 -1
  75. package/src/agent/tool-error-remediation.ts +18 -3
  76. package/src/agent/tools/channel-disengage.ts +1 -1
  77. package/src/agent/tools/channel-edit.ts +1 -1
  78. package/src/agent/tools/channel-fetch-attachment.ts +1 -1
  79. package/src/agent/tools/channel-handoff.ts +3 -2
  80. package/src/agent/tools/channel-history.ts +2 -1
  81. package/src/agent/tools/channel-react.ts +1 -1
  82. package/src/agent/tools/channel-read.ts +36 -3
  83. package/src/agent/tools/channel-reply.ts +1 -1
  84. package/src/agent/tools/channel-send.ts +4 -3
  85. package/src/agent/tools/channel-session-search.ts +13 -4
  86. package/src/agent/tools/grant-role.ts +1 -1
  87. package/src/agent/tools/post-github-review.ts +1 -1
  88. package/src/agent/tools/restart.ts +1 -1
  89. package/src/agent/tools/skip-response.ts +1 -1
  90. package/src/agent/tools/spawn-subagent.ts +15 -1
  91. package/src/agent/tools/stream-snapshot.ts +1 -1
  92. package/src/agent/tools/subagent-cancel.ts +1 -1
  93. package/src/agent/tools/subagent-output.ts +1 -1
  94. package/src/agent/tools/todo/index.ts +1 -1
  95. package/src/agent/tools/webfetch/adaptive-html.ts +6 -4
  96. package/src/agent/tools/webfetch/strategies/readability-child.ts +25 -0
  97. package/src/agent/tools/webfetch/strategies/readability-process.ts +185 -0
  98. package/src/agent/tools/webfetch/tool.ts +6 -5
  99. package/src/agent/tools/websearch.ts +1 -1
  100. package/src/browser/dockerfile.ts +1 -1
  101. package/src/browser/fill-secret.ts +92 -35
  102. package/src/browser/registry.ts +6 -6
  103. package/src/bundled-plugins/agent-messenger-cli-auth/command.ts +211 -0
  104. package/src/bundled-plugins/agent-messenger-cli-auth/index.ts +186 -0
  105. package/src/bundled-plugins/backup/index.ts +17 -2
  106. package/src/bundled-plugins/backup/runner.ts +37 -2
  107. package/src/bundled-plugins/browser-agent/browser-agent.ts +51 -14
  108. package/src/bundled-plugins/browser-agent/index.ts +12 -5
  109. package/src/bundled-plugins/managed-browser/index.ts +25 -2
  110. package/src/bundled-plugins/managed-browser/skills/browserskill/browserskill/SKILL.md +13 -5
  111. package/src/bundled-plugins/managed-browser/skills/omowright/omowright/SKILL.md +56 -5
  112. package/src/bundled-plugins/memory/README.md +23 -2
  113. package/src/bundled-plugins/memory/append-fragment.ts +133 -0
  114. package/src/bundled-plugins/memory/append-tool.ts +80 -149
  115. package/src/bundled-plugins/memory/dreaming.ts +2 -0
  116. package/src/bundled-plugins/memory/index.ts +33 -6
  117. package/src/bundled-plugins/memory/memory-logger.ts +133 -11
  118. package/src/bundled-plugins/memory/references/store-reference-tool.ts +56 -32
  119. package/src/bundled-plugins/memory/remember-tool.ts +81 -0
  120. package/src/bundled-plugins/memory/search-tool-hybrid.ts +91 -0
  121. package/src/bundled-plugins/memory/search-tool.ts +58 -12
  122. package/src/bundled-plugins/memory/stream-events.ts +2 -0
  123. package/src/bundled-plugins/memory/transcript-cursor.ts +30 -0
  124. package/src/bundled-plugins/memory/transcript-preload.ts +131 -26
  125. package/src/bundled-plugins/memory/transcript-view.ts +36 -0
  126. package/src/bundled-plugins/memory/watermark.ts +19 -10
  127. package/src/bundled-plugins/reviewer/reviewer.ts +20 -0
  128. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +3 -6
  129. package/src/bundled-plugins/security/policies/outbound-text.ts +20 -0
  130. package/src/bundled-plugins/security/policies/system-prompt-leak.ts +2 -7
  131. package/src/bundled-plugins/typevault/grants.ts +119 -0
  132. package/src/bundled-plugins/typevault/index.ts +152 -0
  133. package/src/bundled-plugins/typevault/request.ts +87 -0
  134. package/src/bundled-plugins/typevault/runtime.ts +45 -0
  135. package/src/bundled-plugins/typevault/skills/typevault/SKILL.md +65 -0
  136. package/src/channels/adapter-halt.ts +17 -0
  137. package/src/channels/adapters/github/history.ts +23 -2
  138. package/src/channels/adapters/github/inbound.ts +60 -1
  139. package/src/channels/adapters/github/index.ts +27 -5
  140. package/src/channels/adapters/github/reconcile-open-prs.ts +7 -1
  141. package/src/channels/adapters/kakaotalk-author-resolver.ts +7 -5
  142. package/src/channels/adapters/kakaotalk-channel-resolver.ts +45 -15
  143. package/src/channels/adapters/kakaotalk-classify.ts +7 -9
  144. package/src/channels/adapters/kakaotalk-list.ts +62 -0
  145. package/src/channels/adapters/kakaotalk-member-cache.ts +67 -0
  146. package/src/channels/adapters/kakaotalk-membership.ts +27 -10
  147. package/src/channels/adapters/kakaotalk-mention.ts +61 -0
  148. package/src/channels/adapters/kakaotalk.ts +159 -125
  149. package/src/channels/adapters/teams-classify.ts +18 -8
  150. package/src/channels/github-token-bridge.ts +13 -0
  151. package/src/channels/lost-background-context.ts +46 -0
  152. package/src/channels/manager.ts +52 -3
  153. package/src/channels/persistence.ts +5 -0
  154. package/src/channels/router.ts +120 -21
  155. package/src/channels/schema.ts +1 -1
  156. package/src/channels/types.ts +3 -0
  157. package/src/coding-agent/tool.ts +1 -1
  158. package/src/config/config.ts +20 -1
  159. package/src/config/providers.ts +65 -0
  160. package/src/container/start.ts +15 -2
  161. package/src/doctor/channel-checks.ts +33 -0
  162. package/src/doctor/checks.ts +12 -2
  163. package/src/eval/sandbox.ts +3 -0
  164. package/src/eval/tool.ts +1 -0
  165. package/src/git/resolve-identity.ts +67 -2
  166. package/src/git/system-commit.ts +7 -0
  167. package/src/init/dockerfile.ts +5 -1
  168. package/src/init/gitignore.ts +3 -3
  169. package/src/init/index.ts +1 -0
  170. package/src/init/models-dev.ts +2 -0
  171. package/src/init/validate-api-key.ts +5 -0
  172. package/src/migrations/secrets-v1-to-v2.ts +2 -0
  173. package/src/permissions/builtins.ts +8 -0
  174. package/src/plugin/types.ts +6 -0
  175. package/src/run/bundled-plugins.ts +12 -0
  176. package/src/run/channel-session-factory.ts +3 -0
  177. package/src/run/index.ts +13 -2
  178. package/src/sandbox/build.ts +1 -0
  179. package/src/sandbox/canonical-secrets.ts +6 -0
  180. package/src/sandbox/dependency-bins.ts +13 -1
  181. package/src/sandbox/dev-source.ts +21 -12
  182. package/src/sandbox/hidden-paths.ts +1 -1
  183. package/src/sandbox/index.ts +1 -0
  184. package/src/sandbox/policy.ts +5 -0
  185. package/src/secrets/hydrate.ts +4 -1
  186. package/src/secrets/storage.ts +10 -1
  187. package/src/server/command-runner.ts +4 -0
  188. package/src/server/index.ts +8 -1
  189. package/src/skills/typeclaw-config/SKILL.md +16 -0
  190. package/src/skills/typeclaw-memory/SKILL.md +3 -1
  191. package/src/skills/typeclaw-permissions/SKILL.md +8 -8
  192. package/src/skills/typeclaw-troubleshooting/SKILL.md +18 -1
  193. package/src/tunnels/active.ts +14 -0
  194. package/src/typevault/bash-cli.ts +18 -0
  195. package/src/typevault/cli-path.ts +11 -0
  196. package/src/typevault/envelope-helper.ts +17 -0
  197. package/src/typevault/envelope-store.ts +98 -0
  198. package/src/typevault/lifecycle.ts +132 -0
  199. package/src/typevault/prompt-tunnel.ts +33 -0
  200. package/src/typevault/redaction.ts +37 -0
  201. package/src/typevault/vault.ts +283 -0
  202. package/typeclaw.schema.json +40 -10
@@ -1,3 +1,4 @@
1
+ import type { GithubSelfUser } from './adapters/github/auth'
1
2
  import { describeError } from './describe-error'
2
3
  // Decoupled from ChannelRouter on purpose: minting a token for an arbitrary
3
4
  // bash `gh` command is adjacent to channels but is not routing, and a global
@@ -10,8 +11,11 @@ export type GithubTokenResolveResult =
10
11
  | { kind: 'unavailable'; reason: string }
11
12
 
12
13
  export type ResolveGithubTokenForRepo = (repoSlug: string) => Promise<GithubTokenResolveResult>
14
+ export type GetGithubSelf = () => GithubSelfUser | null
13
15
 
14
16
  export type GithubTokenBridge = {
17
+ getSelf: GetGithubSelf
18
+ registerSelf: (self: GithubSelfUser) => () => void
15
19
  resolveTokenForRepo: ResolveGithubTokenForRepo
16
20
  // True when a per-repo App-token minter is registered (only the GitHub App
17
21
  // adapter registers one). This is the non-secret "App auth with per-repo
@@ -38,11 +42,20 @@ const NO_PAT_RESOLVER_REASON =
38
42
  'No GitHub channel PAT is available; the GitHub channel is not configured with PAT auth, or its adapter is not running.'
39
43
 
40
44
  export function createGithubTokenBridge(): GithubTokenBridge {
45
+ let currentSelf: { readonly user: GithubSelfUser } | null = null
41
46
  let current: ((repoSlug: string) => Promise<GithubTokenCredential>) | null = null
42
47
  let currentSelfLogin: (() => string | null) | null = null
43
48
  let currentPat: ((repoSlug: string) => Promise<GithubTokenCredential>) | null = null
44
49
 
45
50
  return {
51
+ getSelf: () => currentSelf?.user ?? null,
52
+ registerSelf: (self) => {
53
+ const registration = { user: self }
54
+ currentSelf = registration
55
+ return () => {
56
+ if (currentSelf === registration) currentSelf = null
57
+ }
58
+ },
46
59
  resolvePatForRepo: async (repoSlug) => {
47
60
  const resolver = currentPat
48
61
  if (resolver === null) return { kind: 'unavailable', reason: NO_PAT_RESOLVER_REASON }
@@ -0,0 +1,46 @@
1
+ import { mkdir, writeFile } from 'node:fs/promises'
2
+ import { join } from 'node:path'
3
+
4
+ import type { BackgroundObligationStore } from './background-obligations'
5
+
6
+ export async function takeLostBackgroundContext(
7
+ agentDir: string,
8
+ obligations: BackgroundObligationStore,
9
+ sessionId: string,
10
+ ): Promise<string[]> {
11
+ const lost = (await obligations.list()).filter(
12
+ (row) =>
13
+ row.parentSessionId === sessionId &&
14
+ row.epoch !== obligations.epoch &&
15
+ row.transfer?.cause !== 'live-turn-ended' &&
16
+ (row.outcome === undefined ||
17
+ (row.outcome.kind === 'intentionally-suppressed' &&
18
+ (row.outcome.reason === 'operator-log-only' || row.outcome.reason === 'adapter-redelivered'))),
19
+ )
20
+ if (lost.length === 0) return []
21
+ const directory = join(agentDir, 'channels', 'lost-background-context')
22
+ await mkdir(directory, { recursive: true })
23
+ const taskIds: string[] = []
24
+ for (const row of lost) {
25
+ try {
26
+ // A separate at-most-once issuance receipt leaves continuity authority untouched.
27
+ // Empty exclusive files also survive another process boot without schema migration.
28
+ await writeFile(join(directory, row.obligationId), '', { flag: 'wx', mode: 0o600 })
29
+ taskIds.push(row.taskId)
30
+ } catch (error) {
31
+ if (error instanceof Error && 'code' in error && error.code === 'EEXIST') continue
32
+ throw error
33
+ }
34
+ }
35
+ if (taskIds.length === 0) return []
36
+ return [
37
+ [
38
+ '---',
39
+ '**[SYSTEM MESSAGE — not from a human]**',
40
+ `Background tasks terminated by a process restart: ${taskIds.join(', ')}.`,
41
+ 'Their results will never arrive. Redo their work if it is still needed.',
42
+ 'Do not acknowledge or reply to this notice.',
43
+ '---',
44
+ ].join('\n'),
45
+ ]
46
+ }
@@ -14,6 +14,7 @@ import { SecretsTeamsCredentialStore } from '@/secrets/teams-store'
14
14
  import { SecretsWebexCredentialStore } from '@/secrets/webex-store'
15
15
  import type { Stream } from '@/stream'
16
16
 
17
+ import { isChannelAdapterHaltedError } from './adapter-halt'
17
18
  import { createDiscordAdapter, type DiscordAdapter } from './adapters/discord'
18
19
  import { createDiscordBotAdapter, type DiscordBotAdapter } from './adapters/discord-bot'
19
20
  import { createGithubAdapter, type GithubAdapter } from './adapters/github'
@@ -211,7 +212,7 @@ type AdapterEntry = {
211
212
  }
212
213
 
213
214
  type FailedAdapter = {
214
- kind: 'start-failed' | 'missing-credentials'
215
+ kind: 'start-failed' | 'missing-credentials' | 'halted'
215
216
  attempts: number
216
217
  failedSinceMs: number
217
218
  nextAttemptAtMs: number
@@ -543,10 +544,11 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
543
544
  } catch (err) {
544
545
  await cleanupPartialStart(adapter)
545
546
  if (!canCommit()) return { status: 'aborted' }
547
+ const halted = isChannelAdapterHaltedError(err)
546
548
  return {
547
549
  status: 'failed',
548
- kind: 'start-failed',
549
- detail: `failed to start: ${describeError(err)}`,
550
+ kind: halted ? 'halted' : 'start-failed',
551
+ detail: halted ? `halted: ${err.message}` : `failed to start: ${describeError(err)}`,
550
552
  inputSignature: buildFailedInputSignature(name, cfg, credentials),
551
553
  }
552
554
  }
@@ -626,6 +628,17 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
626
628
  entry.nextAttemptAtMs = now + delayMs
627
629
  entry.retryQueued = false
628
630
 
631
+ if (failure.kind === 'halted') {
632
+ entry.nextAttemptAtMs = Number.POSITIVE_INFINITY
633
+ logger.error(
634
+ `[channels] adapter "${name}" ${failure.detail}; not retrying automatically. ` +
635
+ 'It starts again when its credentials or config change, on `typeclaw restart`, or on an explicit adapter restart.',
636
+ )
637
+ failed.set(name, entry)
638
+ failedInputSignatures.set(entry, failure.inputSignature)
639
+ return entry
640
+ }
641
+
629
642
  const reachedCap = nominalDelayMs === retryCapMs
630
643
  const justReachedCap = reachedCap && previousNominalDelayMs < retryCapMs
631
644
  if (justReachedCap) entry.nextLogAtMs = now + retryHeartbeatMs
@@ -741,10 +754,43 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
741
754
  return applyStartResult(name, currentCfg, result, previousFailure) ? 'restarted' : 'recovery-pending'
742
755
  }
743
756
 
757
+ // A live adapter that halted itself must leave `live`: the disconnected-restart
758
+ // path below would otherwise log in again every backoff interval forever.
759
+ const retireHaltedAdapter = (name: AdapterId, entry: AdapterEntry, haltReason: string): void => {
760
+ entry.recoveryRestartQueued = true
761
+ const queuedEpoch = lifecycleEpoch
762
+ void runSerially(name, async () => {
763
+ try {
764
+ if (!running || queuedEpoch !== lifecycleEpoch || live.get(name) !== entry) return
765
+ if (!(await stopAdapter(name))) return
766
+ const cfg = options.channelsConfigRef()[name]
767
+ if (cfg === undefined || cfg.enabled === false) return
768
+ // Record the credentials the halted session actually ran with. Re-reading
769
+ // them here would adopt a rotation that landed during stop() as already
770
+ // tried, and the reload carrying it would skip the restart it owes.
771
+ recordFailure(name, cfg, {
772
+ status: 'failed',
773
+ kind: 'halted',
774
+ detail: `halted: ${haltReason}`,
775
+ inputSignature: buildFailedInputSignature(name, cfg, { signature: entry.credentialSignature, missing: [] }),
776
+ })
777
+ } finally {
778
+ if (live.get(name) === entry) entry.recoveryRestartQueued = false
779
+ }
780
+ }).catch((err) => {
781
+ logger.error(`[channels] adapter "${name}" halt supervision failed: ${describeError(err)}`)
782
+ })
783
+ }
784
+
744
785
  const superviseAdapters = (): void => {
745
786
  if (!running) return
746
787
  const now = recoveryNow()
747
788
  for (const [name, entry] of live) {
789
+ const haltReason = 'haltReason' in entry.adapter ? (entry.adapter.haltReason?.() ?? null) : null
790
+ if (haltReason !== null) {
791
+ if (!entry.recoveryRestartQueued) retireHaltedAdapter(name, entry, haltReason)
792
+ continue
793
+ }
748
794
  if (entry.adapter.isConnected()) {
749
795
  void router
750
796
  .recoverWaitingReactions(name)
@@ -1013,6 +1059,9 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
1013
1059
  const changed =
1014
1060
  failedInputSignatures.get(previousFailure) !== buildFailedInputSignature(name, latest, credentials)
1015
1061
  if (changed) failed.delete(name)
1062
+ // A halted adapter only restarts on changed inputs; an unrelated
1063
+ // reload must not send another login to a platform that refused it.
1064
+ else if (previousFailure.kind === 'halted') return named ? 'skipped' : null
1016
1065
  // A queued retry will read the new credential when it fires, so the
1017
1066
  // rotation is on its way even though nothing happened right here.
1018
1067
  else if (previousFailure.retryQueued) return named ? 'recovery-pending' : null
@@ -29,6 +29,10 @@ export type ChannelSessionRecord = {
29
29
  sessionFile?: string
30
30
  lastInboundAt?: number
31
31
  participants: ChannelParticipant[]
32
+ // Set once the bot has delivered a message into this conversation. The live
33
+ // send counter resets on restart and rollover, so this is what keeps a
34
+ // thread the bot already joined from looking like an un-addressed intrusion.
35
+ botParticipated?: true
32
36
  githubReviewRound?: GithubReviewFollowupRound & {
33
37
  status: 'pending' | 'completed'
34
38
  createdAt: number
@@ -247,6 +251,7 @@ function isValidRecord(v: unknown): v is ChannelSessionRecord {
247
251
  (r.sessionFile === undefined || typeof r.sessionFile === 'string') &&
248
252
  (r.lastInboundAt === undefined || typeof r.lastInboundAt === 'number') &&
249
253
  Array.isArray(r.participants) &&
254
+ (r.botParticipated === undefined || r.botParticipated === true) &&
250
255
  (r.githubReviewRound === undefined || isValidGithubReviewRound(r.githubReviewRound, r)) &&
251
256
  (r.githubReviewThreadCloseout === undefined || isValidGithubReviewThreadCloseout(r.githubReviewThreadCloseout, r))
252
257
  )
@@ -10,6 +10,7 @@ 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 {
13
+ type DetectedProviderError,
13
14
  detectHardProviderError,
14
15
  isFailoverWorthy,
15
16
  isTransientProviderFailure,
@@ -84,6 +85,7 @@ import {
84
85
  } from './github-review-verdict-coordinator'
85
86
  import { renderPrVerdictStandDownReminder } from './github-verdict-activity'
86
87
  import { InboundJournal, type InboundRecord, type InboundRef } from './inbound-journal'
88
+ import { takeLostBackgroundContext } from './lost-background-context'
87
89
  import {
88
90
  MEMBERSHIP_COLD_FETCH_TIMEOUT_MS,
89
91
  type MembershipCount,
@@ -272,7 +274,15 @@ export function disengageReactionEmojiFor(adapter: AdapterId): string {
272
274
  return DISENGAGE_REACTION_EMOJI_OVERRIDES[adapter] ?? DISENGAGE_REACTION_EMOJI
273
275
  }
274
276
 
275
- type PendingProviderError = { turnSeq: number; safeMessage: string; retryAndSee: boolean }
277
+ type PendingProviderError = { turnSeq: number; safeMessage: string; retryAndSee: boolean; unclassified: boolean }
278
+
279
+ // Transient overloads share the generic notice text, so the notice alone can't
280
+ // identify a failure nothing is known about; the raw text has to rule them out.
281
+ function providerFailureSurface(err: DetectedProviderError): { retryAndSee: boolean; unclassified: boolean } {
282
+ const transient = isTransientProviderFailure(err.message)
283
+ const unclassified = !transient && isUnclassifiedProviderNotice(err.safeMessage)
284
+ return { retryAndSee: transient || unclassified, unclassified }
285
+ }
276
286
 
277
287
  type SilentAckReason = 'github_review_output' | 'awaiting_background_child'
278
288
 
@@ -769,7 +779,7 @@ type ObservedInbound = {
769
779
 
770
780
  type TimedAttachment = { ts: number; attachment: InboundAttachment; current?: boolean }
771
781
 
772
- type ChannelAgentSession = AgentSession & { getAbortReason?: () => string | undefined }
782
+ type ChannelAgentSession = AgentSession & { getAbortReason?: () => string | undefined; resetLoopGuard?: () => void }
773
783
 
774
784
  // Provenance of a queued system reminder, which decides whether the
775
785
  // reminder-only drain iteration it drives CONTINUES the current logical turn or
@@ -1036,6 +1046,8 @@ type LiveSession = {
1036
1046
  // the drain loop's run condition checks BOTH queues so a system
1037
1047
  // reminder alone is enough to trigger a turn.
1038
1048
  pendingSystemReminders: PendingSystemReminder[]
1049
+ // Passive context only: it must never become work in the reminder queue.
1050
+ restoredBackgroundContextPending: boolean
1039
1051
  // Identity-only cache; every durable transition resolves ownership in its lane.
1040
1052
  backgroundCoverage: string[]
1041
1053
  inboundCoverage: string[]
@@ -1081,6 +1093,9 @@ type LiveSession = {
1081
1093
  // future hard cap without picking a threshold out of thin air.
1082
1094
  sendTimestamps: Map<string, number[]>
1083
1095
  successfulChannelSends: number
1096
+ // Durable twin of `successfulChannelSends > 0`, restored from the persisted
1097
+ // mapping so `botInThread` survives restarts and rollovers.
1098
+ botParticipated: boolean
1084
1099
  // Monotonic per-LiveSession turn counter incremented just before each
1085
1100
  // `live.session.prompt(...)` call in `drain()`. Used as a turn identity
1086
1101
  // so `skip_response` can record "I skipped turn N" without leaking
@@ -1292,7 +1307,7 @@ type LiveSession = {
1292
1307
  // the turn already ran tools. The same failure must not resurface as a
1293
1308
  // live-turn-ended notice, so turn-end settles held coverage silently.
1294
1309
  // Cleared with the other logical-turn state.
1295
- providerErrorSilencedThisLogicalTurn: boolean
1310
+ providerErrorSilencedThisLogicalTurn: 'tool-activity' | 'unclassified-failure' | null
1296
1311
  // Successful, non-communication, non-control tool output observed during
1297
1312
  // this logical turn. Unlike toolExecutionThisLogicalTurn, channel_reply and
1298
1313
  // todo/control calls cannot satisfy a later durable completion claim.
@@ -2970,6 +2985,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2970
2985
  chat: prev.chat,
2971
2986
  thread: prev.thread,
2972
2987
  participants: prev.participants,
2988
+ ...(prev.botParticipated === true ? { botParticipated: true as const } : {}),
2973
2989
  lastInboundAt: 0,
2974
2990
  ...(prev.githubReviewThreadCloseout !== undefined && prev.githubReviewRound !== undefined
2975
2991
  ? { githubReviewRound: prev.githubReviewRound }
@@ -3020,6 +3036,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3020
3036
  chat: record.chat,
3021
3037
  thread: record.thread,
3022
3038
  participants: record.participants,
3039
+ ...(record.botParticipated === true ? { botParticipated: true as const } : {}),
3023
3040
  lastInboundAt: 0,
3024
3041
  ...(record.githubReviewRound !== undefined ? { githubReviewRound: record.githubReviewRound } : {}),
3025
3042
  ...(record.githubReviewThreadCloseout !== undefined
@@ -3052,6 +3069,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3052
3069
  sessionId: resumeTarget.sessionId,
3053
3070
  sessionFile: resumeTarget.sessionFile,
3054
3071
  participants: (record?.participants ?? []) as ChannelParticipant[],
3072
+ ...(record?.botParticipated === true ? { botParticipated: true as const } : {}),
3055
3073
  lastInboundAt: now(),
3056
3074
  ...(record?.githubReviewRound !== undefined ? { githubReviewRound: record.githubReviewRound } : {}),
3057
3075
  ...(record?.githubReviewThreadCloseout !== undefined
@@ -3157,6 +3175,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3157
3175
  ...(transcriptPath ? { sessionFile: basename(transcriptPath) } : {}),
3158
3176
  lastInboundAt: now(),
3159
3177
  participants,
3178
+ ...(resolvedRecord?.botParticipated === true ? { botParticipated: true as const } : {}),
3160
3179
  ...(restoredRound !== null && restoredRoundStatus !== null
3161
3180
  ? (() => {
3162
3181
  const state = githubReviewRoundPersistence(restoredRound, now)
@@ -3217,6 +3236,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3217
3236
  pendingGithubReviewRoundCloseout: null,
3218
3237
  promptQueue: [],
3219
3238
  pendingSystemReminders: [],
3239
+ restoredBackgroundContextPending: !isColdStart,
3220
3240
  backgroundCoverage: [],
3221
3241
  inboundCoverage: [],
3222
3242
  backgroundStopVersion: 0,
@@ -3272,6 +3292,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3272
3292
  lastSendLeafId: null,
3273
3293
  sendTimestamps: new Map(),
3274
3294
  successfulChannelSends: 0,
3295
+ botParticipated: resolvedRecord?.botParticipated === true,
3275
3296
  turnSeq: 0,
3276
3297
  logicalTurnStartedAt: now(),
3277
3298
  coverageDeferredSince: null,
@@ -3297,7 +3318,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3297
3318
  githubReviewOutputTurn: null,
3298
3319
  toolExecutionThisLogicalTurn: false,
3299
3320
  backgroundWakeLogicalTurn: false,
3300
- providerErrorSilencedThisLogicalTurn: false,
3321
+ providerErrorSilencedThisLogicalTurn: null,
3301
3322
  qualifyingWorkThisLogicalTurn: false,
3302
3323
  promisedWorkOutstandingThisLogicalTurn: false,
3303
3324
  statusOutputOutstandingThisLogicalTurn: false,
@@ -3332,7 +3353,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3332
3353
  live.pendingProviderError = {
3333
3354
  turnSeq: live.turnSeq,
3334
3355
  safeMessage: err.safeMessage,
3335
- retryAndSee: isTransientProviderFailure(err.message) || isUnclassifiedProviderNotice(err.safeMessage),
3356
+ ...providerFailureSurface(err),
3336
3357
  }
3337
3358
  })
3338
3359
  live.unsubTodoOutcome = created.session.subscribe((event: unknown) => {
@@ -3481,6 +3502,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3481
3502
  // emitting a misleading elision marker for a zero-length gap.
3482
3503
  const requested = head + tail + 1
3483
3504
  const result = await fetchHistory(live.key.adapter, {
3505
+ workspace: live.key.workspace,
3484
3506
  chat: live.key.chat,
3485
3507
  thread: live.key.thread,
3486
3508
  ...(live.githubReviewRound !== null ? { githubReviewRound: live.githubReviewRound } : {}),
@@ -3520,6 +3542,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3520
3542
  if (tail === 0) return
3521
3543
  head = 0
3522
3544
  const channelResult = await fetchHistory(live.key.adapter, {
3545
+ workspace: live.key.workspace,
3523
3546
  chat: live.key.chat,
3524
3547
  thread: null,
3525
3548
  limit: tail + 1,
@@ -3599,6 +3622,22 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3599
3622
  await persist()
3600
3623
  }
3601
3624
 
3625
+ const persistBotParticipation = async (live: LiveSession): Promise<void> => {
3626
+ if (mappings === null) return
3627
+ const idx = mappings.findIndex(
3628
+ (s) =>
3629
+ s.adapter === live.key.adapter &&
3630
+ s.workspace === live.key.workspace &&
3631
+ s.chat === live.key.chat &&
3632
+ (s.thread ?? null) === (live.key.thread ?? null),
3633
+ )
3634
+ if (idx < 0) return
3635
+ const next = mappings.slice()
3636
+ next[idx] = { ...next[idx]!, botParticipated: true }
3637
+ mappings = next
3638
+ await persist()
3639
+ }
3640
+
3602
3641
  const fireTyping = async (
3603
3642
  live: LiveSession,
3604
3643
  phase: 'tick' | 'stop',
@@ -4218,9 +4257,33 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4218
4257
  const isReviewStateUnknownDeferralActive = (closeout: GithubReviewThreadCloseout): boolean =>
4219
4258
  closeout.deferUntil?.kind === 'review-state-unknown' && closeout.deferUntil.expiresAt > now()
4220
4259
 
4260
+ // The carrier of a pending round may spawn its reviewer before a participant's
4261
+ // reply opens the thread close-out. That reviewer is still the one that will
4262
+ // close the thread, so wait from the round's start, not the obligation's.
4263
+ const closeoutChildWaitStartedAt = (
4264
+ live: LiveSession,
4265
+ closeout: GithubReviewThreadCloseout & { startedAt: number },
4266
+ ): number => {
4267
+ const round = live.githubReviewRound
4268
+ if (
4269
+ round === null ||
4270
+ round.carrierThread !== live.key.thread ||
4271
+ round.workspace !== closeout.workspace ||
4272
+ round.prNumber !== closeout.prNumber
4273
+ ) {
4274
+ return closeout.startedAt
4275
+ }
4276
+ const state = githubReviewRoundPersistence(round, now)
4277
+ if (state?.status !== 'pending') return closeout.startedAt
4278
+ return Math.min(closeout.startedAt, state.createdAt)
4279
+ }
4280
+
4221
4281
  const enforceGithubReviewThreadCloseout = async (live: LiveSession): Promise<void> => {
4222
4282
  const closeout = live.githubReviewThreadCloseout
4223
- if (closeout === null || isAwaitingBackgroundChild(live, 'github-thread-closeout', closeout.startedAt)) {
4283
+ if (
4284
+ closeout === null ||
4285
+ isAwaitingBackgroundChild(live, 'github-thread-closeout', closeoutChildWaitStartedAt(live, closeout))
4286
+ ) {
4224
4287
  return
4225
4288
  }
4226
4289
  if (isReviewStateUnknownDeferralActive(closeout)) {
@@ -4873,7 +4936,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4873
4936
  // record.
4874
4937
  if (live.toolExecutionThisLogicalTurn && !owesPromisedWork(live)) {
4875
4938
  live.pendingProviderError = null
4876
- live.providerErrorSilencedThisLogicalTurn = true
4939
+ live.providerErrorSilencedThisLogicalTurn = 'tool-activity'
4877
4940
  logger.warn(
4878
4941
  `[channels] ${live.keyId}: provider_error_notice_suppressed reason=tool_activity_this_turn notice="${pending.safeMessage}"`,
4879
4942
  )
@@ -4924,6 +4987,17 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4924
4987
  }
4925
4988
  return
4926
4989
  }
4990
+ // The reaction couldn't land (a reaction-less adapter, no reactable target, or
4991
+ // a refused call). An unclassified failure names nothing the user can act on,
4992
+ // so it isn't worth looking broken in the chat: the operator log carries it.
4993
+ // Promised work keeps the notice, since silence would leave the user waiting.
4994
+ if (pending.unclassified && !owesPromisedWork(live)) {
4995
+ live.providerErrorSilencedThisLogicalTurn = 'unclassified-failure'
4996
+ logger.warn(
4997
+ `[channels] ${live.keyId}: provider_error_notice_suppressed reason=unclassified_no_reaction notice="${pending.safeMessage}"`,
4998
+ )
4999
+ return
5000
+ }
4927
5001
  const result = await send(
4928
5002
  {
4929
5003
  adapter: live.key.adapter,
@@ -4958,17 +5032,22 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4958
5032
  // the journal rows stay owed meanwhile.
4959
5033
  // A logical turn that may not error out in the channel: one opened by background
4960
5034
  // work rather than a user, or one whose provider-error notice was already
4961
- // suppressed because it ran tools. Whatever such a turn leaves owed settles
4962
- // silently instead of becoming a live-turn-ended notice, wherever it ends.
5035
+ // suppressed. Whatever such a turn leaves owed settles silently instead of
5036
+ // becoming a live-turn-ended notice, wherever it ends.
4963
5037
  const silentTurnEnd = (live: LiveSession): { log: string; reason: string } | null =>
4964
5038
  live.backgroundWakeLogicalTurn
4965
5039
  ? { log: 'background_wake_turn_ended_silently', reason: 'background-wake-turn-ended' }
4966
- : live.providerErrorSilencedThisLogicalTurn
5040
+ : live.providerErrorSilencedThisLogicalTurn === 'tool-activity'
4967
5041
  ? {
4968
5042
  log: 'turn_end_notice_suppressed reason=provider_error_after_tool_activity',
4969
5043
  reason: 'provider-error-after-tool-activity',
4970
5044
  }
4971
- : null
5045
+ : live.providerErrorSilencedThisLogicalTurn === 'unclassified-failure'
5046
+ ? {
5047
+ log: 'turn_end_notice_suppressed reason=unclassified_provider_failure',
5048
+ reason: 'unclassified-provider-failure',
5049
+ }
5050
+ : null
4972
5051
 
4973
5052
  // Settles a source turn's held rows by their exact generations, for when a fresh
4974
5053
  // batch abandons a silent turn: the rows may be owned by a predecessor session,
@@ -5067,7 +5146,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5067
5146
  live.githubReviewOutputTurn = null
5068
5147
  live.toolExecutionThisLogicalTurn = false
5069
5148
  live.backgroundWakeLogicalTurn = true
5070
- live.providerErrorSilencedThisLogicalTurn = false
5149
+ live.providerErrorSilencedThisLogicalTurn = null
5071
5150
  live.qualifyingWorkThisLogicalTurn = false
5072
5151
  }
5073
5152
 
@@ -5523,7 +5602,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5523
5602
  live.githubReviewOutputTurn = null
5524
5603
  live.toolExecutionThisLogicalTurn = false
5525
5604
  live.backgroundWakeLogicalTurn = false
5526
- live.providerErrorSilencedThisLogicalTurn = false
5605
+ live.providerErrorSilencedThisLogicalTurn = null
5527
5606
  live.qualifyingWorkThisLogicalTurn = false
5528
5607
  live.promisedWorkOutstandingThisLogicalTurn = false
5529
5608
  live.statusOutputOutstandingThisLogicalTurn = false
@@ -5596,6 +5675,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5596
5675
  live.policyDeniedToolSendsThisTurn.clear()
5597
5676
  resetReviewTurn(live.sessionId)
5598
5677
  const isRealUserTurn = batch.length > 0
5678
+ // Only a fresh inbound batch is a new request. Retry and wakeup turns
5679
+ // (empty batch, reminders only) keep the loop guard's history so a
5680
+ // stranded or aborted cycle cannot clear itself through a retry.
5681
+ if (isRealUserTurn) live.session.resetLoopGuard?.()
5599
5682
  await awaitLatestTodoOutcomeWrite(live)
5600
5683
  await recordTodoTurnStart(live, isRealUserTurn)
5601
5684
  const retrievalQuery = composeRetrievalQuery(batch)
@@ -5618,7 +5701,16 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5618
5701
  )
5619
5702
  })
5620
5703
  if (!accountMayPrompt || live.backgroundStopVersion !== stopVersion) continue
5621
- const promptText = retrievalContext.results.length > 0 ? `${text}\n\n${retrievalContext.results}` : text
5704
+ // Taken only once this turn will prompt: the receipt is at-most-once.
5705
+ const restoredContext = live.restoredBackgroundContextPending
5706
+ ? await takeLostBackgroundContext(options.agentDir, backgroundObligations, live.sessionId)
5707
+ : []
5708
+ live.restoredBackgroundContextPending = false
5709
+ const promptText = [
5710
+ ...restoredContext,
5711
+ text,
5712
+ ...(retrievalContext.results ? [retrievalContext.results] : []),
5713
+ ].join('\n\n')
5622
5714
  applyTurnThinkingLevel(live.session, retrievalQuery, live.turnThinkingDefault, live.lastQuestionSignal)
5623
5715
  live.promptInFlight = true
5624
5716
  try {
@@ -5716,9 +5808,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5716
5808
  live.pendingProviderError = {
5717
5809
  turnSeq: live.turnSeq,
5718
5810
  safeMessage: hardProviderError.safeMessage,
5719
- retryAndSee:
5720
- isTransientProviderFailure(hardProviderError.message) ||
5721
- isUnclassifiedProviderNotice(hardProviderError.safeMessage),
5811
+ ...providerFailureSurface(hardProviderError),
5722
5812
  }
5723
5813
  }
5724
5814
  live.consecutiveSends.clear()
@@ -6429,7 +6519,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6429
6519
  }
6430
6520
 
6431
6521
  const hasBotParticipated = (live: LiveSession): boolean => {
6432
- if (live.successfulChannelSends > 0) return true
6522
+ if (live.botParticipated || live.successfulChannelSends > 0) return true
6433
6523
  // Only OUR own prefetched history counts as participation — matching any
6434
6524
  // bot here let a PEER bot's buffered message flip botInThread=true,
6435
6525
  // neutralizing the replyToOtherMessageId suppressor and engaging us in a
@@ -7531,6 +7621,12 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
7531
7621
 
7532
7622
  if (live) {
7533
7623
  live.successfulChannelSends++
7624
+ if (!live.botParticipated) {
7625
+ live.botParticipated = true
7626
+ void persistBotParticipation(live).catch((err) => {
7627
+ logger.warn(`[channels] ${live.keyId}: persisting bot participation failed: ${describeError(err)}`)
7628
+ })
7629
+ }
7534
7630
  // Promise fulfillment follows OUTPUT KIND, never source:
7535
7631
  // (a) ordinary substantive tool output clears;
7536
7632
  // (b) multilingual continuation-willingness/status output preserves, and
@@ -9285,7 +9381,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
9285
9381
  const round = publisher?.githubReviewRound ?? persistedPublisher?.githubReviewRound
9286
9382
  if (round === null || round === undefined) {
9287
9383
  const resetRound = resetGithubReviewRoundCompletionForPr(args.workspace, args.prNumber, now)
9288
- if (resetRound !== null) persistMatchingGithubReviewRound(resetRound)
9384
+ // A first review never carries a round, so its verdict lands here every
9385
+ // time. Only a pending round the publisher failed to hold is worth a warning.
9386
+ if (resetRound === null) return { kind: 'no-round' }
9387
+ persistMatchingGithubReviewRound(resetRound)
9289
9388
  logger.warn(
9290
9389
  `[channels] github review round completion rejected pr=${args.workspace}#${args.prNumber} verdict=${args.verdict}: no publisher session with round state session=${args.sessionId}`,
9291
9390
  )
@@ -9546,7 +9645,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
9546
9645
  // Answers a failed turn with a reaction on its triggering message instead of
9547
9646
  // a chat line; in busy rooms the old text notices outnumbered real replies.
9548
9647
  // False when there is nothing reactable or the adapter refused, so the caller
9549
- // falls back to its text notice and the user is never left with silence.
9648
+ // decides whether the failure still earns its text notice.
9550
9649
  const reactTurnFailed = async (live: LiveSession): Promise<boolean> => {
9551
9650
  const reactionRef = live.currentTurnReactionRef
9552
9651
  if (reactionRef === null) return false
@@ -9559,7 +9658,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
9559
9658
  emoji: TURN_FAILED_REACTION_EMOJI,
9560
9659
  })
9561
9660
  if (!result.ok && result.code !== 'unsupported') {
9562
- logger.info(`[channels] ${live.keyId}: turn-failed reaction failed, posting notice: ${result.error}`)
9661
+ logger.info(`[channels] ${live.keyId}: turn-failed reaction failed: ${result.error}`)
9563
9662
  }
9564
9663
  return result.ok
9565
9664
  }
@@ -33,7 +33,7 @@ export const ADAPTER_READ_CAPABILITIES: Record<AdapterId, readonly ReadCapabilit
33
33
  github: ['history'],
34
34
  instagram: ['history'],
35
35
  line: ['history'],
36
- kakaotalk: ['history'],
36
+ kakaotalk: ['history', 'list'],
37
37
  slack: ['history'],
38
38
  'slack-bot': ['history', 'message-get', 'list'],
39
39
  teams: ['history'],
@@ -515,6 +515,9 @@ export type ChannelHistoryMessage = {
515
515
  }
516
516
 
517
517
  export type FetchHistoryArgs = {
518
+ // Adapters whose chat ids repeat across workspaces (GitHub `pr:12` in every
519
+ // repo) need it to address the right conversation. Callers that know it pass it.
520
+ workspace?: string
518
521
  chat: string
519
522
  thread: string | null
520
523
  limit: number
@@ -1,5 +1,5 @@
1
- import { Type } from '@earendil-works/pi-ai'
2
1
  import { defineTool } from '@earendil-works/pi-coding-agent'
2
+ import { Type } from 'typebox'
3
3
 
4
4
  import type { SessionOrigin } from '@/agent/session-origin'
5
5
  import type { PermissionService } from '@/permissions'
@@ -219,7 +219,8 @@ const dockerfileObjectSchema = z.object({
219
219
  // restart, so the happy path still works; only hand-edited configs need to
220
220
  // set it explicitly. When the binary is absent at tunnel start, the
221
221
  // provider fails with a clear "enable docker.file.cloudflared and restart"
222
- // message rather than a cryptic spawn error.
222
+ // message rather than a cryptic spawn error. An enabled `typevault` installs
223
+ // it regardless, for the secret-page tunnel it opens at boot.
223
224
  cloudflared: z.boolean().default(false),
224
225
  // Install xvfb so the entrypoint shim can spawn an Xvfb virtual X
225
226
  // server and export DISPLAY, giving headed Chrome (agent-browser
@@ -321,6 +322,21 @@ export const githubCliSchema = githubCliObjectSchema.default(() => githubCliObje
321
322
 
322
323
  export type GithubCliConfig = z.infer<typeof githubCliSchema>
323
324
 
325
+ // Experimental. When enabled, `typeclaw start` moves secrets.json into the
326
+ // agent's own TypeVault vault (.typevault/); disabling restores the file.
327
+ const typevaultObjectSchema = z
328
+ .object({
329
+ enabled: z.boolean().default(false),
330
+ // Container port for the one-time secret page. The daemon binds it on the
331
+ // first request, so a clash with another listener only shows up then.
332
+ promptPort: z.number().int().min(1).max(65535).default(8976),
333
+ })
334
+ .strict()
335
+
336
+ export const typevaultSchema = typevaultObjectSchema.default(() => typevaultObjectSchema.parse({}))
337
+
338
+ export type TypevaultConfig = z.infer<typeof typevaultSchema>
339
+
324
340
  export const DEFAULT_LOG_RETENTION_DAYS = 14
325
341
  export const MAX_LOG_RETENTION_DAYS = 3650
326
342
 
@@ -890,6 +906,7 @@ export const configSchema = z
890
906
  browser: browserSchema,
891
907
  git: gitSchema,
892
908
  githubCli: githubCliSchema,
909
+ typevault: typevaultSchema,
893
910
  logs: logsSchema,
894
911
  roles: rolesConfigSchema.optional(),
895
912
  tunnels: tunnelsArraySchema,
@@ -1183,6 +1200,7 @@ export const FIELD_EFFECTS: Record<string, FieldEffect> = {
1183
1200
  browser: 'restart-required',
1184
1201
  'git.ignore': 'restart-required',
1185
1202
  githubCli: 'restart-required',
1203
+ typevault: 'restart-required',
1186
1204
  logs: 'ignored',
1187
1205
  // Split: `match` lists are reload-safe (typeclaw role claim, hand-edits
1188
1206
  // adding/removing match rules apply without a container restart);
@@ -1283,6 +1301,7 @@ export function extractPluginConfigs(raw: unknown): Record<string, unknown> {
1283
1301
  'docker',
1284
1302
  'git',
1285
1303
  'githubCli',
1304
+ 'typevault',
1286
1305
  'logs',
1287
1306
  'roles',
1288
1307
  'permissions',