typeclaw 0.48.12 → 0.49.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 (213) hide show
  1. package/package.json +6 -3
  2. package/scripts/dump-system-prompt.ts +52 -110
  3. package/src/agent/attention-escalation.ts +8 -5
  4. package/src/agent/auth-reloadable.ts +2 -3
  5. package/src/agent/auth.ts +59 -79
  6. package/src/agent/compaction.ts +2 -2
  7. package/src/agent/index.ts +173 -85
  8. package/src/agent/live-sessions.ts +2 -2
  9. package/src/agent/live-subagents.ts +1 -0
  10. package/src/agent/llm-replay-sanitizer.ts +1 -1
  11. package/src/agent/model-overrides.ts +1 -1
  12. package/src/agent/multimodal/look-at.ts +3 -3
  13. package/src/agent/multimodal/read-redirect.ts +1 -1
  14. package/src/agent/plugin-tools.ts +76 -39
  15. package/src/agent/prompt-cache-key.ts +42 -0
  16. package/src/agent/provider-error.ts +179 -10
  17. package/src/agent/reload-tool.ts +1 -1
  18. package/src/agent/restart-handoff/index.ts +7 -14
  19. package/src/agent/reviewer-activity.ts +68 -0
  20. package/src/agent/session-origin.ts +33 -0
  21. package/src/agent/subagents.ts +14 -2
  22. package/src/agent/system-prompt.ts +68 -202
  23. package/src/agent/todo/continuation-policy.ts +12 -4
  24. package/src/agent/tool-error-remediation.ts +1 -1
  25. package/src/agent/tool-file-safety.ts +113 -14
  26. package/src/agent/tool-not-found-nudge.ts +1 -1
  27. package/src/agent/tool-result-budget.ts +2 -2
  28. package/src/agent/tools/channel-disengage.ts +2 -2
  29. package/src/agent/tools/channel-edit.ts +2 -2
  30. package/src/agent/tools/channel-fetch-attachment.ts +2 -2
  31. package/src/agent/tools/channel-history-render.ts +2 -1
  32. package/src/agent/tools/channel-history.ts +2 -2
  33. package/src/agent/tools/channel-react.ts +2 -2
  34. package/src/agent/tools/channel-read.ts +2 -2
  35. package/src/agent/tools/channel-reply.ts +25 -7
  36. package/src/agent/tools/channel-send.ts +51 -9
  37. package/src/agent/tools/curl-impersonate.ts +11 -2
  38. package/src/agent/tools/grant-role.ts +2 -2
  39. package/src/agent/tools/post-github-review.ts +79 -17
  40. package/src/agent/tools/restart.ts +2 -2
  41. package/src/agent/tools/skip-response.ts +4 -4
  42. package/src/agent/tools/spawn-subagent.ts +165 -14
  43. package/src/agent/tools/stream-snapshot.ts +2 -2
  44. package/src/agent/tools/subagent-cancel.ts +2 -2
  45. package/src/agent/tools/subagent-output.ts +10 -2
  46. package/src/agent/tools/todo/index.ts +2 -2
  47. package/src/agent/tools/webfetch/tool.ts +2 -2
  48. package/src/agent/tools/websearch.ts +2 -2
  49. package/src/bundled-plugins/backup/README.md +10 -9
  50. package/src/bundled-plugins/backup/runner.ts +140 -58
  51. package/src/bundled-plugins/backup/subagents.ts +58 -26
  52. package/src/bundled-plugins/github-cli-auth/gh-command.ts +34 -2
  53. package/src/bundled-plugins/github-cli-auth/granted-push.ts +135 -0
  54. package/src/bundled-plugins/github-cli-auth/index.ts +83 -11
  55. package/src/bundled-plugins/github-cli-auth/review-account.ts +23 -0
  56. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +9 -2
  57. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +45 -7
  58. package/src/bundled-plugins/operator/operator.ts +15 -4
  59. package/src/bundled-plugins/reviewer/skills/code-review.ts +1 -1
  60. package/src/bundled-plugins/security/index.ts +50 -2
  61. package/src/bundled-plugins/security/policies/git-exfil.ts +24 -12
  62. package/src/channels/adapters/discord-bot-reactions.ts +18 -0
  63. package/src/channels/adapters/discord-bot.ts +122 -67
  64. package/src/channels/adapters/discord-reactions.ts +18 -0
  65. package/src/channels/adapters/discord.ts +114 -8
  66. package/src/channels/adapters/github/inbound.ts +103 -8
  67. package/src/channels/adapters/github/index.ts +251 -19
  68. package/src/channels/adapters/github/last-alive.ts +27 -0
  69. package/src/channels/adapters/github/outbound.ts +54 -18
  70. package/src/channels/adapters/github/pending-review-store.ts +141 -0
  71. package/src/channels/adapters/github/permission-guidance.ts +1 -0
  72. package/src/channels/adapters/github/reactions.ts +100 -0
  73. package/src/channels/adapters/github/reconcile-cooldown-store.ts +197 -67
  74. package/src/channels/adapters/github/reconcile-open-prs.ts +418 -33
  75. package/src/channels/adapters/github/recovery.ts +106 -0
  76. package/src/channels/adapters/github/review-check.ts +510 -0
  77. package/src/channels/adapters/github/review-submitter.ts +34 -2
  78. package/src/channels/adapters/instagram.ts +32 -14
  79. package/src/channels/adapters/kakaotalk.ts +22 -7
  80. package/src/channels/adapters/line.ts +18 -3
  81. package/src/channels/adapters/outbound-account.ts +20 -0
  82. package/src/channels/adapters/own-reactions.ts +66 -0
  83. package/src/channels/adapters/recovery-correlation.ts +214 -0
  84. package/src/channels/adapters/slack-bot-classify.ts +18 -11
  85. package/src/channels/adapters/slack-bot-dedupe.ts +111 -28
  86. package/src/channels/adapters/slack-bot-reactions.ts +18 -0
  87. package/src/channels/adapters/slack-bot.ts +125 -57
  88. package/src/channels/adapters/slack-classify.ts +25 -4
  89. package/src/channels/adapters/slack-inbound-revision.ts +96 -0
  90. package/src/channels/adapters/slack-reactions.ts +18 -0
  91. package/src/channels/adapters/slack-thread-ts.ts +6 -0
  92. package/src/channels/adapters/slack.ts +48 -3
  93. package/src/channels/adapters/teams.ts +14 -4
  94. package/src/channels/adapters/telegram-bot.ts +56 -10
  95. package/src/channels/adapters/webex-bot.ts +12 -2
  96. package/src/channels/adapters/webex.ts +12 -2
  97. package/src/channels/background-handoff.ts +434 -0
  98. package/src/channels/background-obligations.ts +893 -0
  99. package/src/channels/continuity-types.ts +271 -0
  100. package/src/channels/github-review-check.ts +598 -0
  101. package/src/channels/github-review-turn-ledger.ts +102 -28
  102. package/src/channels/github-review-verdict-coordinator.ts +96 -13
  103. package/src/channels/github-token-bridge.ts +11 -5
  104. package/src/channels/inbound-journal.ts +1738 -0
  105. package/src/channels/index.ts +6 -1
  106. package/src/channels/manager.ts +17 -7
  107. package/src/channels/recovery-dispatcher.ts +264 -0
  108. package/src/channels/recovery-notice.ts +94 -0
  109. package/src/channels/recovery-outbox.ts +459 -0
  110. package/src/channels/router.ts +2582 -633
  111. package/src/channels/schema.ts +8 -1
  112. package/src/channels/subagent-completion-bridge.ts +17 -14
  113. package/src/channels/types.ts +121 -16
  114. package/src/channels/waiting-reactions.ts +664 -0
  115. package/src/cli/compose.ts +7 -4
  116. package/src/cli/hostd.ts +49 -3
  117. package/src/cli/inspect.ts +11 -14
  118. package/src/cli/model.ts +7 -5
  119. package/src/cli/oauth-callbacks.ts +38 -23
  120. package/src/coding-agent/broker-body.ts +38 -0
  121. package/src/coding-agent/broker.ts +290 -0
  122. package/src/coding-agent/claude.ts +95 -0
  123. package/src/coding-agent/codex.ts +104 -0
  124. package/src/coding-agent/index.ts +506 -0
  125. package/src/coding-agent/omo-state.ts +69 -0
  126. package/src/coding-agent/omo-stream.ts +98 -0
  127. package/src/coding-agent/omo.ts +192 -0
  128. package/src/coding-agent/runner.ts +263 -0
  129. package/src/coding-agent/tool.ts +62 -0
  130. package/src/coding-agent/worktree.ts +355 -0
  131. package/src/compose/restart.ts +10 -3
  132. package/src/compose/start.ts +20 -3
  133. package/src/config/config.ts +70 -26
  134. package/src/config/providers.ts +278 -50
  135. package/src/container/exit-reason.ts +44 -0
  136. package/src/container/index.ts +5 -0
  137. package/src/container/log-archive.ts +51 -13
  138. package/src/container/memory-limit.ts +1 -1
  139. package/src/container/memory-oversubscription.ts +36 -6
  140. package/src/container/oom-events.ts +86 -0
  141. package/src/container/restart.ts +2 -0
  142. package/src/container/shared.ts +8 -1
  143. package/src/container/start.ts +25 -13
  144. package/src/container/stop.ts +6 -2
  145. package/src/container/tool-oom-priority.ts +32 -0
  146. package/src/cron/consumer.ts +10 -4
  147. package/src/cron/reloadable.ts +23 -2
  148. package/src/doctor/checks.ts +14 -2
  149. package/src/hostd/daemon.ts +20 -10
  150. package/src/hostd/spawn.ts +106 -5
  151. package/src/hostd/version.ts +20 -0
  152. package/src/hostd/watchdog.ts +241 -0
  153. package/src/init/dockerfile.ts +57 -592
  154. package/src/init/index.ts +6 -7
  155. package/src/init/oauth-login.ts +57 -17
  156. package/src/inspect/transcript-view.ts +6 -3
  157. package/src/mcp/client.ts +3 -1
  158. package/src/operations/classify-tool-outcome.ts +45 -1
  159. package/src/operations/incidents.ts +10 -5
  160. package/src/plugin/core-tool-names.ts +1 -1
  161. package/src/plugin/define.ts +1 -0
  162. package/src/plugin/index.ts +1 -0
  163. package/src/plugin/types.ts +6 -1
  164. package/src/run/background-handoff-boot.ts +86 -0
  165. package/src/run/channel-session-factory.ts +5 -4
  166. package/src/run/index.ts +93 -93
  167. package/src/run/resource-sample.ts +19 -0
  168. package/src/sandbox/build.ts +4 -0
  169. package/src/sandbox/coding-agent.ts +214 -0
  170. package/src/sandbox/policy.ts +1 -0
  171. package/src/sandbox/runtime-private.ts +4 -1
  172. package/src/secrets/coding-agent-auth.ts +97 -0
  173. package/src/secrets/index.ts +0 -16
  174. package/src/secrets/refresh-provider-oauth.ts +30 -76
  175. package/src/secrets/schema.ts +3 -4
  176. package/src/secrets/storage.ts +133 -234
  177. package/src/server/command-runner.ts +6 -2
  178. package/src/server/index.ts +102 -41
  179. package/src/sessions/index.ts +1 -1
  180. package/src/skills/typeclaw-channel-github/SKILL.md +7 -5
  181. package/src/skills/typeclaw-claude-code/SKILL.md +25 -260
  182. package/src/skills/typeclaw-claude-code/references/auth-flow.md +7 -23
  183. package/src/skills/typeclaw-claude-code/references/headless-sessions.md +11 -0
  184. package/src/skills/typeclaw-claude-code/references/results-and-worktrees.md +13 -0
  185. package/src/skills/typeclaw-codex-cli/SKILL.md +35 -270
  186. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +13 -20
  187. package/src/skills/typeclaw-codex-cli/references/headless-sessions.md +26 -0
  188. package/src/skills/typeclaw-codex-cli/references/results-and-worktrees.md +28 -0
  189. package/src/skills/typeclaw-config/SKILL.md +24 -24
  190. package/src/skills/typeclaw-config/references/dockerfile.md +14 -13
  191. package/src/skills/typeclaw-cron/SKILL.md +1 -1
  192. package/src/skills/typeclaw-github-contributing/SKILL.md +2 -2
  193. package/src/skills/typeclaw-memory/SKILL.md +3 -3
  194. package/src/skills/typeclaw-omo-cli/SKILL.md +52 -0
  195. package/src/skills/typeclaw-omo-cli/references/auth-flow.md +11 -0
  196. package/src/skills/typeclaw-omo-cli/references/headless-sessions.md +11 -0
  197. package/src/skills/typeclaw-omo-cli/references/results-and-worktrees.md +23 -0
  198. package/src/skills/typeclaw-plugins/SKILL.md +20 -20
  199. package/src/skills/typeclaw-skills/SKILL.md +19 -2
  200. package/src/skills/typeclaw-troubleshooting/SKILL.md +15 -2
  201. package/src/tui/index.ts +5 -3
  202. package/src/tui/theme.ts +1 -1
  203. package/typeclaw.schema.json +44 -2
  204. package/src/agent/adaptive-thinking-compat.ts +0 -79
  205. package/src/secrets/claude-credentials-json.ts +0 -129
  206. package/src/secrets/codex-auth-json.ts +0 -102
  207. package/src/secrets/export-claude-credentials-file.ts +0 -270
  208. package/src/secrets/export-codex-auth-file.ts +0 -250
  209. package/src/secrets/oauth-xai.ts +0 -348
  210. package/src/skills/typeclaw-claude-code/references/stop-hook.md +0 -101
  211. package/src/skills/typeclaw-claude-code/references/tmux-driving.md +0 -243
  212. package/src/skills/typeclaw-codex-cli/references/stop-hook.md +0 -92
  213. package/src/skills/typeclaw-codex-cli/references/tmux-driving.md +0 -239
@@ -0,0 +1,506 @@
1
+ import { constants } from 'node:fs'
2
+ import { open, lstat } from 'node:fs/promises'
3
+ import { join } from 'node:path'
4
+
5
+ import { z } from 'zod'
6
+
7
+ import type { SessionOrigin } from '@/agent/session-origin'
8
+ import { getConfig, resolveModel } from '@/config'
9
+ import { KNOWN_PROVIDERS } from '@/config/providers'
10
+ import type { PermissionService } from '@/permissions'
11
+ import { resolveHiddenPaths } from '@/sandbox/hidden-paths'
12
+ import { createCodingAgentAuthResolver, type CodingAgentAuthResolver } from '@/secrets/coding-agent-auth'
13
+
14
+ import { CLAUDE_AUXILIARY_MODELS, CLAUDE_CODE_VERSION } from './claude'
15
+ import { CODEX_CLI_VERSION } from './codex'
16
+ import { OMO_CLI_VERSION, omoModelSchema } from './omo'
17
+ import { runCodingAgent, type CodingRunOptions, type CodingRunResult } from './runner'
18
+ import {
19
+ captureCodingChanges,
20
+ codingGitExecutor,
21
+ createCodingWorkspace,
22
+ createTaskDirectory,
23
+ disposeCodingWorkspace,
24
+ resolveCodingSource,
25
+ writeCodingArtifact,
26
+ writeTaskRegistry,
27
+ type ChangeArtifacts,
28
+ type CodingExecutor,
29
+ type CodingWorkspace,
30
+ } from './worktree'
31
+
32
+ export const codingRequestSchema = z.discriminatedUnion('action', [
33
+ z.strictObject({
34
+ action: z.literal('run'),
35
+ engine: z.enum(['claude', 'codex', 'omo']),
36
+ repo: z.string().min(1).optional(),
37
+ modelRef: z.string().min(1).optional(),
38
+ taskId: z.string().uuid().optional(),
39
+ prompt: z.string().min(1).max(1_000_000),
40
+ mode: z.enum(['plan', 'code']).optional(),
41
+ timeoutSeconds: z.number().finite().positive().max(2_147_483.647).default(1800),
42
+ }),
43
+ z.strictObject({ action: z.literal('result'), taskId: z.string().uuid() }),
44
+ z.strictObject({ action: z.literal('dispose'), taskId: z.string().uuid(), discard: z.literal(true) }),
45
+ ])
46
+ export type CodingRequest = z.infer<typeof codingRequestSchema>
47
+ const taskSchema = z
48
+ .object({
49
+ // PR2 registries predate the engine field and contain only Claude tasks.
50
+ engine: z.enum(['claude', 'codex', 'omo']).default('claude'),
51
+ provider: z.enum(['anthropic', 'openai-codex']).optional(),
52
+ modelMetadata: omoModelSchema.optional(),
53
+ taskId: z.string().uuid(),
54
+ ownerSessionId: z.string(),
55
+ parentSessionId: z.string().optional(),
56
+ principal: z.string(),
57
+ role: z.string(),
58
+ modelRef: z.string(),
59
+ model: z.string(),
60
+ mode: z.enum(['plan', 'code']),
61
+ permissions: z.array(z.string()),
62
+ allowedModels: z.array(z.string()),
63
+ engineVersion: z.string(),
64
+ source: z.string(),
65
+ sourceIdentity: z.string(),
66
+ baseSha: z.string(),
67
+ sessionId: z.string().uuid().optional(),
68
+ state: z.enum(['running', 'completed', 'incomplete', 'failed', 'cancelled', 'interrupted']),
69
+ finalMessage: z.string().default(''),
70
+ exitCode: z.number().nullable().default(null),
71
+ diagnostic: z.string().default(''),
72
+ changedFiles: z.array(z.string()).default([]),
73
+ untrackedFiles: z.array(z.string()).default([]),
74
+ oversized: z.boolean().default(false),
75
+ })
76
+ .refine((task) => task.engine !== 'omo' || (task.provider !== undefined && task.modelMetadata?.id === task.model), {
77
+ message: 'OmO tasks require recorded provider and model metadata.',
78
+ })
79
+ .transform((task) => ({
80
+ ...task,
81
+ provider: task.provider ?? (task.engine === 'claude' ? ('anthropic' as const) : ('openai-codex' as const)),
82
+ }))
83
+ const ENGINE_VERSIONS = { claude: CLAUDE_CODE_VERSION, codex: CODEX_CLI_VERSION, omo: OMO_CLI_VERSION } as const
84
+ const ENGINE_TOGGLES = { claude: 'claudeCode', codex: 'codexCli', omo: 'omoCli' } as const
85
+ type CodingTask = z.infer<typeof taskSchema>
86
+ export type CodingCaller = {
87
+ readonly sessionId: string
88
+ readonly origin: SessionOrigin | undefined
89
+ readonly permissions: PermissionService
90
+ readonly onPrepared?: (receipt: Record<string, unknown>) => void
91
+ }
92
+ type ServiceDependencies = {
93
+ auth?: () => Promise<CodingAgentAuthResolver>
94
+ executor?: (source: string, root: string, signal?: AbortSignal) => CodingExecutor
95
+ run?: (options: CodingRunOptions) => Promise<CodingRunResult>
96
+ writeArtifact?: (path: string, text: string) => Promise<void>
97
+ sourcePath?: (source: string) => string
98
+ }
99
+
100
+ export class CodingAgentService {
101
+ private readonly tasks = new Map<string, CodingTask>()
102
+ private readonly active = new Map<string, { controller: AbortController; done: Promise<void> }>()
103
+ private readonly ready: Promise<void>
104
+ private auth: Promise<CodingAgentAuthResolver> | undefined
105
+ private saving: Promise<void> = Promise.resolve()
106
+ private stopped = false
107
+ private registryUnavailable = false
108
+
109
+ constructor(
110
+ readonly agentDir: string,
111
+ private readonly dependencies: ServiceDependencies = {},
112
+ ) {
113
+ this.ready = this.load().catch(() => {
114
+ this.registryUnavailable = true
115
+ })
116
+ }
117
+
118
+ async execute(request: CodingRequest, caller: CodingCaller, signal?: AbortSignal): Promise<Record<string, unknown>> {
119
+ await this.ready
120
+ if (this.stopped) throw new Error('Coding delegation is shutting down.')
121
+ if (this.registryUnavailable)
122
+ throw new Error('Coding task registry is unreadable. The host operator must repair it before delegation resumes.')
123
+ authorize(caller, this.agentDir)
124
+ if (request.action === 'result') {
125
+ const task = this.tasks.get(request.taskId)
126
+ if (!task) throw new Error('Unknown coding task.')
127
+ this.authorizeTask(task, caller)
128
+ if (task.state !== 'interrupted' || this.active.has(task.taskId)) return this.receipt(task)
129
+ }
130
+ const id = request.taskId ?? crypto.randomUUID()
131
+ if (this.active.has(id)) throw new Error('Coding task already running.')
132
+ const controller = new AbortController()
133
+ const combined = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal
134
+ let finish: () => void = () => {}
135
+ const done = new Promise<void>((resolve) => {
136
+ finish = resolve
137
+ })
138
+ this.active.set(id, { controller, done })
139
+ const timer = setTimeout(
140
+ () => controller.abort(new DOMException('Coding invocation timed out', 'TimeoutError')),
141
+ request.action === 'run' ? request.timeoutSeconds * 1000 : 60_000,
142
+ )
143
+ try {
144
+ return await this.executeRequest(request, caller, combined, id)
145
+ } finally {
146
+ clearTimeout(timer)
147
+ this.active.delete(id)
148
+ finish()
149
+ }
150
+ }
151
+
152
+ private async executeRequest(
153
+ request: CodingRequest,
154
+ caller: CodingCaller,
155
+ signal?: AbortSignal,
156
+ creationId?: string,
157
+ ): Promise<Record<string, unknown>> {
158
+ if (request.action === 'run' && !request.taskId) {
159
+ if (!creationId) throw new Error('Missing coding task identity.')
160
+ return this.create(request, caller, creationId, signal)
161
+ }
162
+ const task = this.tasks.get(request.taskId ?? '')
163
+ if (!task) throw new Error('Unknown coding task.')
164
+ this.authorizeTask(task, caller)
165
+ if (request.action === 'result') {
166
+ const workspace = this.workspace(task)
167
+ const writeArtifact =
168
+ this.dependencies.writeArtifact ??
169
+ ((path: string, text: string) => writeCodingArtifact(this.agentDir, path, text))
170
+ const execute =
171
+ this.dependencies.executor?.(task.source, workspace.taskRoot, signal) ??
172
+ codingGitExecutor(task.source, workspace.taskRoot, signal, 'plan')
173
+ try {
174
+ Object.assign(task, await captureCodingChanges(workspace, execute, writeArtifact))
175
+ await this.save()
176
+ } catch {
177
+ return {
178
+ ...this.receipt(task),
179
+ diagnostic:
180
+ 'Runtime was interrupted. Current diff recovery failed; inspect the retained worktree before resuming.',
181
+ }
182
+ }
183
+ return this.receipt(task)
184
+ }
185
+ switch (request.action) {
186
+ case 'dispose': {
187
+ await disposeCodingWorkspace(this.workspace(task), this.executor(task))
188
+ this.tasks.delete(task.taskId)
189
+ await this.save()
190
+ return { ok: true, taskId: task.taskId, state: 'disposed' }
191
+ }
192
+ case 'run':
193
+ await resolveCodingSource(
194
+ this.agentDir,
195
+ task.source,
196
+ getConfig().mounts.map((mount) => mount.name),
197
+ )
198
+ if (
199
+ request.engine !== task.engine ||
200
+ (request.modelRef && request.modelRef !== task.modelRef) ||
201
+ (request.repo && request.repo !== task.source)
202
+ ) {
203
+ throw new Error('A resumed task keeps its recorded engine, repository and model.')
204
+ }
205
+ if (task.engineVersion !== ENGINE_VERSIONS[task.engine])
206
+ throw new Error('Task CLI version changed; preserve and review its diff before migrating.')
207
+ if (!task.sessionId)
208
+ throw new Error('This task has no resumable CLI session. Its partial work remains available.')
209
+ task.mode = request.mode ?? task.mode
210
+ return this.invoke(task, request, signal)
211
+ }
212
+ }
213
+
214
+ async stop(): Promise<void> {
215
+ this.stopped = true
216
+ const runs = [...this.active.values()]
217
+ for (const run of runs) run.controller.abort()
218
+ await Promise.allSettled(runs.map((run) => run.done))
219
+ await this.saving
220
+ }
221
+
222
+ private async create(
223
+ request: Extract<CodingRequest, { action: 'run' }>,
224
+ caller: CodingCaller,
225
+ taskId: string,
226
+ signal?: AbortSignal,
227
+ ) {
228
+ if (!request.repo || !request.modelRef)
229
+ throw new Error('A new task requires repo and a concrete engine-compatible modelRef.')
230
+ const config = getConfig()
231
+ const toggle = ENGINE_TOGGLES[request.engine]
232
+ const provider =
233
+ request.engine === 'omo'
234
+ ? request.modelRef.startsWith('anthropic/')
235
+ ? 'anthropic'
236
+ : request.modelRef.startsWith('openai-codex/')
237
+ ? 'openai-codex'
238
+ : undefined
239
+ : request.engine === 'claude'
240
+ ? 'anthropic'
241
+ : 'openai-codex'
242
+ if (!config.docker.file[toggle] && !this.dependencies.run) {
243
+ throw new Error(`Enable docker.file.${toggle} on the host and run \`typeclaw start\` to rebuild the image.`)
244
+ }
245
+ if (!provider)
246
+ throw new Error('OmO requires an anthropic or openai-codex modelRef; other providers are not brokered.')
247
+ if (
248
+ !request.modelRef.startsWith(`${provider}/`) ||
249
+ !(
250
+ request.modelRef.slice(provider.length + 1) in KNOWN_PROVIDERS[provider].models ||
251
+ request.modelRef in config.customModels
252
+ )
253
+ )
254
+ throw new Error(`Select a configured or curated ${provider} modelRef.`)
255
+ const resolvedModel = resolveModel(request.modelRef)
256
+ const model = resolvedModel.id
257
+ const source = await resolveCodingSource(
258
+ this.agentDir,
259
+ request.repo,
260
+ config.mounts.map((mount) => mount.name),
261
+ )
262
+ // Missing auth never creates a task, exits the runtime, or disables another provider.
263
+ await (await this.resolver()).resolve(signal, undefined, provider)
264
+ const taskRoot = await createTaskDirectory(this.agentDir, taskId)
265
+ const identity = await lstat(source)
266
+ const task: CodingTask = {
267
+ engine: request.engine,
268
+ provider,
269
+ ...(request.engine === 'omo' ? { modelMetadata: omoModelSchema.parse(resolvedModel) } : {}),
270
+ taskId,
271
+ ownerSessionId: caller.sessionId,
272
+ ...(caller.origin?.kind === 'subagent' ? { parentSessionId: caller.origin.parentSessionId } : {}),
273
+ principal: principal(caller.origin),
274
+ role: caller.permissions.resolveRole(caller.origin),
275
+ permissions: [...caller.permissions.describe(caller.origin).permissions],
276
+ modelRef: request.modelRef,
277
+ model,
278
+ mode: request.mode ?? 'code',
279
+ allowedModels: [...new Set([model, ...(request.engine === 'claude' ? CLAUDE_AUXILIARY_MODELS : [])])],
280
+ engineVersion: ENGINE_VERSIONS[request.engine],
281
+ source,
282
+ sourceIdentity: `${identity.dev}:${identity.ino}`,
283
+ baseSha: '',
284
+ state: 'running',
285
+ finalMessage: '',
286
+ diagnostic: '',
287
+ changedFiles: [],
288
+ untrackedFiles: [],
289
+ exitCode: null,
290
+ oversized: false,
291
+ }
292
+ this.tasks.set(taskId, task)
293
+ await this.save()
294
+ try {
295
+ const workspace = await createCodingWorkspace(
296
+ source,
297
+ taskRoot,
298
+ this.dependencies.executor?.(source, taskRoot, signal) ??
299
+ codingGitExecutor(source, taskRoot, signal, 'snapshot'),
300
+ this.dependencies.sourcePath?.(source),
301
+ )
302
+ task.baseSha = workspace.baseSha
303
+ task.sourceIdentity = workspace.sourceIdentity
304
+ } catch (error) {
305
+ task.state = signal?.aborted ? 'incomplete' : 'failed'
306
+ task.diagnostic =
307
+ error instanceof Error ? error.message : 'Source snapshot failed; the task directory is preserved.'
308
+ await this.save()
309
+ return this.receipt(task)
310
+ }
311
+ caller.onPrepared?.(this.receipt(task))
312
+ return this.invoke(task, request, signal)
313
+ }
314
+
315
+ private async invoke(task: CodingTask, request: Extract<CodingRequest, { action: 'run' }>, signal?: AbortSignal) {
316
+ const combined = signal ?? new AbortController().signal
317
+ const workspace = this.workspace(task)
318
+ const writeArtifact =
319
+ this.dependencies.writeArtifact ??
320
+ ((path: string, text: string) => writeCodingArtifact(this.agentDir, path, text))
321
+ try {
322
+ const source = await lstat(task.source)
323
+ if (`${source.dev}:${source.ino}` !== task.sourceIdentity) throw new Error('Source repository identity changed.')
324
+ const auth = await this.resolver()
325
+ await auth.resolve(combined, undefined, task.provider)
326
+ task.state = 'running'
327
+ await this.save()
328
+ const result = await (this.dependencies.run ?? runCodingAgent)({
329
+ engine: task.engine,
330
+ provider: task.provider,
331
+ ...(task.modelMetadata ? { modelMetadata: task.modelMetadata } : {}),
332
+ workspace,
333
+ auth,
334
+ model: task.model,
335
+ allowedModels: task.allowedModels,
336
+ sessionId: task.sessionId ?? crypto.randomUUID(),
337
+ resume: task.sessionId !== undefined,
338
+ mode: task.mode,
339
+ prompt: request.prompt,
340
+ timeoutSeconds: request.timeoutSeconds,
341
+ signal: combined,
342
+ writeArtifact,
343
+ })
344
+ Object.assign(task, result)
345
+ // Collect the diff even after cancellation; the child has already been killed and reaped.
346
+ const artifactExecutor =
347
+ this.dependencies.executor?.(task.source, workspace.taskRoot) ??
348
+ codingGitExecutor(task.source, workspace.taskRoot, undefined, 'plan')
349
+ const artifacts: ChangeArtifacts = await captureCodingChanges(workspace, artifactExecutor, writeArtifact)
350
+ Object.assign(task, artifacts)
351
+ if (artifacts.oversized) {
352
+ task.state = 'incomplete'
353
+ task.diagnostic =
354
+ 'Change artifact exceeds 64 MiB; inspect the retained worktree. No truncated patch was produced.'
355
+ }
356
+ await writeArtifact(
357
+ join(workspace.taskRoot, 'output', 'result.json'),
358
+ JSON.stringify(this.receipt(task), null, 2),
359
+ )
360
+ return this.receipt(task)
361
+ } catch (error) {
362
+ task.state = combined.aborted
363
+ ? combined.reason instanceof DOMException && combined.reason.name === 'TimeoutError'
364
+ ? 'incomplete'
365
+ : 'cancelled'
366
+ : 'failed'
367
+ task.diagnostic = error instanceof Error ? error.message : 'Coding task failed; partial work is preserved.'
368
+ return this.receipt(task)
369
+ } finally {
370
+ await this.save()
371
+ }
372
+ }
373
+
374
+ private authorizeTask(task: CodingTask, caller: CodingCaller): void {
375
+ const samePrincipal = task.principal === principal(caller.origin)
376
+ const sameScope = task.ownerSessionId === caller.sessionId || task.parentSessionId === caller.sessionId
377
+ const current = caller.permissions.describe(caller.origin).permissions
378
+ if (!samePrincipal || !sameScope || !task.permissions.every((permission) => current.includes(permission))) {
379
+ throw new Error('Coding task belongs to a different caller or authority scope.')
380
+ }
381
+ }
382
+
383
+ private workspace(task: CodingTask): CodingWorkspace {
384
+ return {
385
+ source: task.source,
386
+ sourceIdentity: task.sourceIdentity,
387
+ baseSha: task.baseSha,
388
+ taskRoot: join(this.agentDir, 'workspace', 'coding-agents', task.taskId),
389
+ }
390
+ }
391
+
392
+ private executor(task: CodingTask): CodingExecutor {
393
+ return (this.dependencies.executor ?? codingGitExecutor)(task.source, this.workspace(task).taskRoot)
394
+ }
395
+
396
+ private receipt(task: CodingTask): Record<string, unknown> {
397
+ const root = this.workspace(task).taskRoot
398
+ return {
399
+ ok: task.state === 'completed',
400
+ taskId: task.taskId,
401
+ state: task.state,
402
+ baseSha: task.baseSha,
403
+ source: task.source,
404
+ engine: task.engine,
405
+ provider: task.provider,
406
+ modelRef: task.modelRef,
407
+ engineVersion: task.engineVersion,
408
+ worktreePath: join(root, 'worktree'),
409
+ finalMessage: task.finalMessage,
410
+ changedFiles: task.changedFiles,
411
+ untrackedFiles: task.untrackedFiles,
412
+ patchPath: task.oversized ? null : join(root, 'output', 'changes.patch'),
413
+ exitCode: task.exitCode,
414
+ diagnostic: task.diagnostic,
415
+ warning: 'This task uses committed HEAD only; uncommitted source changes are excluded.',
416
+ oversized: task.oversized,
417
+ }
418
+ }
419
+
420
+ private resolver(): Promise<CodingAgentAuthResolver> {
421
+ this.auth ??= (this.dependencies.auth ?? (() => createCodingAgentAuthResolver(this.agentDir)))().catch((error) => {
422
+ this.auth = undefined
423
+ throw error
424
+ })
425
+ return this.auth
426
+ }
427
+
428
+ private async load(): Promise<void> {
429
+ const path = join(this.agentDir, '.typeclaw', 'coding-agent-tasks.json')
430
+ const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW).catch((error: unknown) => {
431
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return undefined
432
+ throw error
433
+ })
434
+ if (!file) return
435
+ try {
436
+ const text = await file.readFile('utf8')
437
+ if (!text.trim()) return
438
+ for (const task of z.array(taskSchema).parse(JSON.parse(text))) {
439
+ if (task.state === 'running') {
440
+ task.state = 'interrupted'
441
+ task.diagnostic = 'Runtime restarted; resume explicitly with a fresh invocation.'
442
+ }
443
+ this.tasks.set(task.taskId, task)
444
+ }
445
+ } finally {
446
+ await file.close()
447
+ }
448
+ }
449
+
450
+ private save(): Promise<void> {
451
+ const text = JSON.stringify([...this.tasks.values()])
452
+ this.saving = this.saving.then(() =>
453
+ writeTaskRegistry(join(this.agentDir, '.typeclaw', 'coding-agent-tasks.json'), text),
454
+ )
455
+ return this.saving
456
+ }
457
+ }
458
+
459
+ function authorize(caller: CodingCaller, agentDir: string): void {
460
+ const origin = caller.origin
461
+ if (
462
+ !origin ||
463
+ (origin.kind !== 'tui' && origin.kind !== 'channel' && origin.kind !== 'subagent') ||
464
+ !caller.permissions.has(origin, 'subagent.spawn') ||
465
+ resolveHiddenPaths(caller.permissions, origin, agentDir).dirs.includes(join(agentDir, 'workspace'))
466
+ ) {
467
+ throw new Error('Coding delegation requires subagent.spawn and private workspace access.')
468
+ }
469
+ principal(origin)
470
+ }
471
+
472
+ function principal(origin: SessionOrigin | undefined): string {
473
+ let root = origin
474
+ for (let depth = 0; root?.kind === 'subagent' && depth < 8; depth++) root = root.spawnedByOrigin
475
+ if (root?.kind === 'tui') return JSON.stringify(['tui', root.sessionId])
476
+ if (root?.kind === 'channel' && root.lastInboundAuthorId) {
477
+ return JSON.stringify([root.adapter, root.workspace, root.chat, root.thread, root.lastInboundAuthorId])
478
+ }
479
+ throw new Error('Coding delegation requires an attributable interactive caller.')
480
+ }
481
+
482
+ const services = new Map<string, { service: CodingAgentService; owners: number }>()
483
+ export function getCodingAgentService(agentDir: string): CodingAgentService {
484
+ let entry = services.get(agentDir)
485
+ if (!entry) {
486
+ entry = { service: new CodingAgentService(agentDir), owners: 0 }
487
+ services.set(agentDir, entry)
488
+ }
489
+ return entry.service
490
+ }
491
+ export function retainCodingAgentService(agentDir: string): () => Promise<void> {
492
+ const service = getCodingAgentService(agentDir)
493
+ const entry = services.get(agentDir)
494
+ if (!entry) throw new Error('Coding service was not initialized.')
495
+ entry.owners++
496
+ let released = false
497
+ return async () => {
498
+ if (released) return
499
+ released = true
500
+ entry.owners--
501
+ if (entry.owners === 0) {
502
+ services.delete(agentDir)
503
+ await service.stop()
504
+ }
505
+ }
506
+ }
@@ -0,0 +1,69 @@
1
+ import { constants } from 'node:fs'
2
+ import { mkdir, open, readdir, type FileHandle } from 'node:fs/promises'
3
+ import { join } from 'node:path'
4
+
5
+ import { z } from 'zod'
6
+
7
+ import { createAndOpenAnchoredDirectory } from '@/agent/tool-file-safety'
8
+ import { assertCodingDirectory } from '@/sandbox/coding-agent'
9
+
10
+ const DIRECTORIES = [
11
+ 'home',
12
+ 'home/.omo',
13
+ 'agent',
14
+ 'sessions',
15
+ 'task-state',
16
+ 'tmp',
17
+ 'config',
18
+ 'cache',
19
+ 'data',
20
+ 'state',
21
+ ] as const
22
+
23
+ export async function prepareOmoDirectories(configDir: string): Promise<void> {
24
+ for (const part of ['', ...DIRECTORIES]) {
25
+ const path = join(configDir, part)
26
+ if (process.platform === 'linux') {
27
+ const directory = await createAndOpenAnchoredDirectory(path)
28
+ await directory.close()
29
+ } else {
30
+ // Dev-stage fixtures only; production execution still requires Linux bwrap.
31
+ await mkdir(path, { recursive: true, mode: 0o700 })
32
+ await assertCodingDirectory(path)
33
+ }
34
+ }
35
+ }
36
+
37
+ export async function hasOmoSession(configDir: string, sessionId: string, cwd: string): Promise<boolean> {
38
+ const directory = join(configDir, 'sessions')
39
+ let anchor: FileHandle | undefined
40
+ try {
41
+ if (process.platform === 'linux') anchor = await createAndOpenAnchoredDirectory(directory, false)
42
+ else await assertCodingDirectory(directory)
43
+ const root = anchor ? `/proc/self/fd/${anchor.fd}` : directory
44
+ const files = (await readdir(root)).filter((name) => name.endsWith(`_${sessionId}.jsonl`))
45
+ if (files.length !== 1 || !files[0]) return false
46
+ const file = await open(join(root, files[0]), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
47
+ try {
48
+ const stat = await file.stat()
49
+ if (!stat.isFile() || stat.nlink !== 1) return false
50
+ // Read only the bounded session header, never the model-controlled body.
51
+ const buffer = Buffer.alloc(16 * 1024)
52
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0)
53
+ const text = buffer.subarray(0, bytesRead).toString('utf8')
54
+ const newline = text.indexOf('\n')
55
+ if (newline < 0) return false
56
+ const header = z
57
+ .object({ type: z.literal('session'), version: z.literal(3), id: z.string().uuid(), cwd: z.string() })
58
+ .parse(JSON.parse(text.slice(0, newline)))
59
+ return header.id === sessionId && header.cwd === cwd
60
+ } finally {
61
+ await file.close()
62
+ }
63
+ } catch {
64
+ // Unsafe or missing state must never silently start a new conversation.
65
+ return false
66
+ } finally {
67
+ await anchor?.close()
68
+ }
69
+ }
@@ -0,0 +1,98 @@
1
+ import { z } from 'zod'
2
+
3
+ const eventSchema = z.object({ type: z.string().min(1) }).passthrough()
4
+ const messageSchema = z.object({ role: z.string() }).passthrough()
5
+ const assistantSchema = z.object({
6
+ role: z.literal('assistant'),
7
+ content: z.array(z.object({ type: z.string(), text: z.string().optional() }).passthrough()),
8
+ stopReason: z.enum(['stop', 'length', 'toolUse', 'error', 'aborted']),
9
+ })
10
+ const sessionSchema = z.object({
11
+ type: z.literal('session'),
12
+ version: z.literal(3),
13
+ id: z.string().uuid(),
14
+ cwd: z.string(),
15
+ })
16
+
17
+ export class OmoStreamParser {
18
+ sessionId: string | undefined
19
+ finalMessage = ''
20
+ terminal = false
21
+ failed = false
22
+ permissionDenied = false
23
+ malformed = false
24
+ private pending = ''
25
+
26
+ constructor(private readonly expected: { readonly sessionId: string; readonly cwd: string }) {}
27
+
28
+ push(text: string): void {
29
+ this.pending += text
30
+ let newline: number
31
+ while ((newline = this.pending.indexOf('\n')) !== -1) {
32
+ if (newline > 4 * 1024 * 1024) throw new Error('OmO event exceeds the 4 MiB event limit.')
33
+ const line = this.pending.slice(0, newline)
34
+ this.pending = this.pending.slice(newline + 1)
35
+ this.line(line)
36
+ }
37
+ if (this.pending.length > 4 * 1024 * 1024) throw new Error('OmO event exceeds the 4 MiB event limit.')
38
+ }
39
+
40
+ finish(): void {
41
+ // The pinned print-mode protocol always flushes newline-delimited records.
42
+ if (this.pending.trim()) this.malformed = true
43
+ this.pending = ''
44
+ }
45
+
46
+ private line(line: string): void {
47
+ if (!line.trim()) return
48
+ try {
49
+ const event = eventSchema.parse(JSON.parse(line))
50
+ switch (event.type) {
51
+ case 'session': {
52
+ const session = sessionSchema.parse(event)
53
+ if (session.id !== this.expected.sessionId || session.cwd !== this.expected.cwd || this.sessionId) {
54
+ this.malformed = true
55
+ } else this.sessionId = session.id
56
+ break
57
+ }
58
+ case 'agent_start':
59
+ this.terminal = false
60
+ this.failed = false
61
+ this.finalMessage = ''
62
+ break
63
+ case 'message_end': {
64
+ const { message } = z.object({ message: messageSchema }).parse(event)
65
+ if (message.role === 'assistant') assistantSchema.parse(message)
66
+ break
67
+ }
68
+ case 'tool_execution_end':
69
+ // Failed tools may be recovered by the agent. Keep their structured
70
+ // events in the JSONL artifact, not as a terminal English heuristic.
71
+ z.object({ toolCallId: z.string(), toolName: z.string(), isError: z.boolean(), result: z.unknown() }).parse(
72
+ event,
73
+ )
74
+ break
75
+ case 'agent_end': {
76
+ const end = z.object({ messages: z.array(messageSchema), willRetry: z.boolean().optional() }).parse(event)
77
+ const assistants = end.messages
78
+ .filter((message) => message.role === 'assistant')
79
+ .map((message) => assistantSchema.parse(message))
80
+ const final = assistants.at(-1)
81
+ this.terminal = false
82
+ this.failed = false
83
+ this.finalMessage = ''
84
+ if (end.willRetry || !final) break
85
+ this.finalMessage = final.content
86
+ .filter((block) => block.type === 'text')
87
+ .map((block) => z.string().parse(block.text))
88
+ .join('\n')
89
+ this.failed = final.stopReason === 'error' || final.stopReason === 'aborted'
90
+ this.terminal = final.stopReason === 'stop' || this.failed
91
+ break
92
+ }
93
+ }
94
+ } catch {
95
+ this.malformed = true
96
+ }
97
+ }
98
+ }