typeclaw 0.48.13 → 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 (176) hide show
  1. package/package.json +5 -5
  2. package/scripts/dump-system-prompt.ts +52 -110
  3. package/src/agent/index.ts +144 -72
  4. package/src/agent/live-sessions.ts +2 -2
  5. package/src/agent/live-subagents.ts +1 -0
  6. package/src/agent/plugin-tools.ts +53 -11
  7. package/src/agent/prompt-cache-key.ts +42 -0
  8. package/src/agent/provider-error.ts +179 -10
  9. package/src/agent/restart-handoff/index.ts +7 -14
  10. package/src/agent/reviewer-activity.ts +68 -0
  11. package/src/agent/session-origin.ts +33 -0
  12. package/src/agent/subagents.ts +13 -1
  13. package/src/agent/system-prompt.ts +68 -202
  14. package/src/agent/todo/continuation-policy.ts +12 -4
  15. package/src/agent/tool-file-safety.ts +113 -14
  16. package/src/agent/tool-not-found-nudge.ts +1 -1
  17. package/src/agent/tools/channel-history-render.ts +2 -1
  18. package/src/agent/tools/channel-reply.ts +23 -5
  19. package/src/agent/tools/channel-send.ts +49 -7
  20. package/src/agent/tools/curl-impersonate.ts +11 -2
  21. package/src/agent/tools/post-github-review.ts +77 -15
  22. package/src/agent/tools/skip-response.ts +2 -2
  23. package/src/agent/tools/spawn-subagent.ts +163 -12
  24. package/src/agent/tools/subagent-output.ts +8 -0
  25. package/src/bundled-plugins/backup/README.md +10 -9
  26. package/src/bundled-plugins/backup/runner.ts +140 -58
  27. package/src/bundled-plugins/backup/subagents.ts +58 -26
  28. package/src/bundled-plugins/github-cli-auth/gh-command.ts +34 -2
  29. package/src/bundled-plugins/github-cli-auth/granted-push.ts +135 -0
  30. package/src/bundled-plugins/github-cli-auth/index.ts +83 -11
  31. package/src/bundled-plugins/github-cli-auth/review-account.ts +23 -0
  32. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +9 -2
  33. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +45 -7
  34. package/src/bundled-plugins/operator/operator.ts +15 -4
  35. package/src/bundled-plugins/reviewer/skills/code-review.ts +1 -1
  36. package/src/bundled-plugins/security/index.ts +50 -2
  37. package/src/bundled-plugins/security/policies/git-exfil.ts +24 -12
  38. package/src/channels/adapters/discord-bot-reactions.ts +18 -0
  39. package/src/channels/adapters/discord-bot.ts +122 -67
  40. package/src/channels/adapters/discord-reactions.ts +18 -0
  41. package/src/channels/adapters/discord.ts +114 -8
  42. package/src/channels/adapters/github/inbound.ts +103 -8
  43. package/src/channels/adapters/github/index.ts +251 -19
  44. package/src/channels/adapters/github/last-alive.ts +27 -0
  45. package/src/channels/adapters/github/outbound.ts +54 -18
  46. package/src/channels/adapters/github/pending-review-store.ts +141 -0
  47. package/src/channels/adapters/github/permission-guidance.ts +1 -0
  48. package/src/channels/adapters/github/reactions.ts +100 -0
  49. package/src/channels/adapters/github/reconcile-cooldown-store.ts +197 -67
  50. package/src/channels/adapters/github/reconcile-open-prs.ts +418 -33
  51. package/src/channels/adapters/github/recovery.ts +106 -0
  52. package/src/channels/adapters/github/review-check.ts +510 -0
  53. package/src/channels/adapters/github/review-submitter.ts +34 -2
  54. package/src/channels/adapters/instagram.ts +32 -14
  55. package/src/channels/adapters/kakaotalk.ts +22 -7
  56. package/src/channels/adapters/line.ts +18 -3
  57. package/src/channels/adapters/outbound-account.ts +20 -0
  58. package/src/channels/adapters/own-reactions.ts +66 -0
  59. package/src/channels/adapters/recovery-correlation.ts +214 -0
  60. package/src/channels/adapters/slack-bot-classify.ts +18 -11
  61. package/src/channels/adapters/slack-bot-dedupe.ts +111 -28
  62. package/src/channels/adapters/slack-bot-reactions.ts +18 -0
  63. package/src/channels/adapters/slack-bot.ts +125 -57
  64. package/src/channels/adapters/slack-classify.ts +25 -4
  65. package/src/channels/adapters/slack-inbound-revision.ts +96 -0
  66. package/src/channels/adapters/slack-reactions.ts +18 -0
  67. package/src/channels/adapters/slack-thread-ts.ts +6 -0
  68. package/src/channels/adapters/slack.ts +48 -3
  69. package/src/channels/adapters/teams.ts +14 -4
  70. package/src/channels/adapters/telegram-bot.ts +56 -10
  71. package/src/channels/adapters/webex-bot.ts +12 -2
  72. package/src/channels/adapters/webex.ts +12 -2
  73. package/src/channels/background-handoff.ts +434 -0
  74. package/src/channels/background-obligations.ts +893 -0
  75. package/src/channels/continuity-types.ts +271 -0
  76. package/src/channels/github-review-check.ts +598 -0
  77. package/src/channels/github-review-turn-ledger.ts +102 -28
  78. package/src/channels/github-review-verdict-coordinator.ts +72 -12
  79. package/src/channels/github-token-bridge.ts +11 -5
  80. package/src/channels/inbound-journal.ts +1738 -0
  81. package/src/channels/index.ts +6 -1
  82. package/src/channels/manager.ts +17 -7
  83. package/src/channels/recovery-dispatcher.ts +264 -0
  84. package/src/channels/recovery-notice.ts +94 -0
  85. package/src/channels/recovery-outbox.ts +459 -0
  86. package/src/channels/router.ts +2539 -615
  87. package/src/channels/schema.ts +8 -1
  88. package/src/channels/subagent-completion-bridge.ts +17 -14
  89. package/src/channels/types.ts +121 -16
  90. package/src/channels/waiting-reactions.ts +664 -0
  91. package/src/cli/compose.ts +7 -4
  92. package/src/cli/hostd.ts +49 -3
  93. package/src/cli/inspect.ts +11 -14
  94. package/src/coding-agent/broker-body.ts +38 -0
  95. package/src/coding-agent/broker.ts +290 -0
  96. package/src/coding-agent/claude.ts +95 -0
  97. package/src/coding-agent/codex.ts +104 -0
  98. package/src/coding-agent/index.ts +506 -0
  99. package/src/coding-agent/omo-state.ts +69 -0
  100. package/src/coding-agent/omo-stream.ts +98 -0
  101. package/src/coding-agent/omo.ts +192 -0
  102. package/src/coding-agent/runner.ts +263 -0
  103. package/src/coding-agent/tool.ts +62 -0
  104. package/src/coding-agent/worktree.ts +355 -0
  105. package/src/compose/restart.ts +10 -3
  106. package/src/compose/start.ts +20 -3
  107. package/src/config/config.ts +10 -3
  108. package/src/config/providers.ts +12 -9
  109. package/src/container/exit-reason.ts +44 -0
  110. package/src/container/index.ts +5 -0
  111. package/src/container/log-archive.ts +51 -13
  112. package/src/container/memory-limit.ts +1 -1
  113. package/src/container/memory-oversubscription.ts +36 -6
  114. package/src/container/oom-events.ts +86 -0
  115. package/src/container/restart.ts +2 -0
  116. package/src/container/shared.ts +8 -1
  117. package/src/container/start.ts +25 -13
  118. package/src/container/stop.ts +6 -2
  119. package/src/container/tool-oom-priority.ts +32 -0
  120. package/src/cron/consumer.ts +10 -4
  121. package/src/cron/reloadable.ts +23 -2
  122. package/src/doctor/checks.ts +14 -2
  123. package/src/hostd/daemon.ts +20 -10
  124. package/src/hostd/spawn.ts +106 -5
  125. package/src/hostd/version.ts +20 -0
  126. package/src/hostd/watchdog.ts +241 -0
  127. package/src/init/dockerfile.ts +57 -592
  128. package/src/init/index.ts +2 -3
  129. package/src/mcp/client.ts +3 -1
  130. package/src/operations/classify-tool-outcome.ts +45 -1
  131. package/src/operations/incidents.ts +10 -5
  132. package/src/plugin/core-tool-names.ts +1 -1
  133. package/src/plugin/define.ts +1 -0
  134. package/src/plugin/index.ts +1 -0
  135. package/src/plugin/types.ts +6 -1
  136. package/src/run/background-handoff-boot.ts +86 -0
  137. package/src/run/index.ts +83 -83
  138. package/src/run/resource-sample.ts +19 -0
  139. package/src/sandbox/build.ts +4 -0
  140. package/src/sandbox/coding-agent.ts +214 -0
  141. package/src/sandbox/policy.ts +1 -0
  142. package/src/sandbox/runtime-private.ts +4 -1
  143. package/src/secrets/coding-agent-auth.ts +97 -0
  144. package/src/secrets/index.ts +0 -16
  145. package/src/server/command-runner.ts +6 -2
  146. package/src/server/index.ts +101 -40
  147. package/src/skills/typeclaw-channel-github/SKILL.md +7 -5
  148. package/src/skills/typeclaw-claude-code/SKILL.md +25 -260
  149. package/src/skills/typeclaw-claude-code/references/auth-flow.md +7 -23
  150. package/src/skills/typeclaw-claude-code/references/headless-sessions.md +11 -0
  151. package/src/skills/typeclaw-claude-code/references/results-and-worktrees.md +13 -0
  152. package/src/skills/typeclaw-codex-cli/SKILL.md +35 -270
  153. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +13 -20
  154. package/src/skills/typeclaw-codex-cli/references/headless-sessions.md +26 -0
  155. package/src/skills/typeclaw-codex-cli/references/results-and-worktrees.md +28 -0
  156. package/src/skills/typeclaw-config/SKILL.md +21 -21
  157. package/src/skills/typeclaw-config/references/dockerfile.md +14 -13
  158. package/src/skills/typeclaw-cron/SKILL.md +1 -1
  159. package/src/skills/typeclaw-github-contributing/SKILL.md +2 -2
  160. package/src/skills/typeclaw-memory/SKILL.md +3 -3
  161. package/src/skills/typeclaw-omo-cli/SKILL.md +52 -0
  162. package/src/skills/typeclaw-omo-cli/references/auth-flow.md +11 -0
  163. package/src/skills/typeclaw-omo-cli/references/headless-sessions.md +11 -0
  164. package/src/skills/typeclaw-omo-cli/references/results-and-worktrees.md +23 -0
  165. package/src/skills/typeclaw-plugins/SKILL.md +15 -15
  166. package/src/skills/typeclaw-skills/SKILL.md +19 -2
  167. package/src/skills/typeclaw-troubleshooting/SKILL.md +15 -2
  168. package/typeclaw.schema.json +12 -1
  169. package/src/secrets/claude-credentials-json.ts +0 -129
  170. package/src/secrets/codex-auth-json.ts +0 -102
  171. package/src/secrets/export-claude-credentials-file.ts +0 -270
  172. package/src/secrets/export-codex-auth-file.ts +0 -250
  173. package/src/skills/typeclaw-claude-code/references/stop-hook.md +0 -101
  174. package/src/skills/typeclaw-claude-code/references/tmux-driving.md +0 -243
  175. package/src/skills/typeclaw-codex-cli/references/stop-hook.md +0 -92
  176. package/src/skills/typeclaw-codex-cli/references/tmux-driving.md +0 -239
@@ -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
+ }
@@ -0,0 +1,192 @@
1
+ import { join } from 'node:path'
2
+
3
+ import { z } from 'zod'
4
+
5
+ import type { CodingAgentProvider } from '@/secrets/coding-agent-auth'
6
+
7
+ import { CLAUDE_CODE_VERSION } from './claude'
8
+
9
+ export const OMO_CLI_VERSION = '5.1.19'
10
+
11
+ // Only metadata understood by the pinned Senpi transport crosses this boundary.
12
+ // Never copy provider URLs, headers, keys, or fallback chains from model records.
13
+ export const omoModelSchema = z.object({
14
+ id: z.string().min(1),
15
+ name: z.string(),
16
+ reasoning: z.boolean(),
17
+ input: z.array(z.enum(['text', 'image'])),
18
+ contextWindow: z.number().positive(),
19
+ maxTokens: z.number().positive(),
20
+ cost: z.object({
21
+ input: z.number(),
22
+ output: z.number(),
23
+ cacheRead: z.number(),
24
+ cacheWrite: z.number(),
25
+ }),
26
+ thinkingLevelMap: z.record(z.string(), z.union([z.string(), z.null()])).optional(),
27
+ compat: z
28
+ .object({
29
+ supportsEagerToolInputStreaming: z.boolean().optional(),
30
+ supportsLongCacheRetention: z.boolean().optional(),
31
+ sendSessionAffinityHeaders: z.boolean().optional(),
32
+ supportsCacheControlOnTools: z.boolean().optional(),
33
+ supportsDisabledThinking: z.boolean().optional(),
34
+ supportsTemperature: z.boolean().optional(),
35
+ supportsToolChoice: z.boolean().optional(),
36
+ supportsForcedToolChoice: z.boolean().optional(),
37
+ forceAdaptiveThinking: z.boolean().optional(),
38
+ allowEmptySignature: z.boolean().optional(),
39
+ supportsToolReferences: z.boolean().optional(),
40
+ supportsDeveloperRole: z.boolean().optional(),
41
+ })
42
+ .optional(),
43
+ })
44
+ export type OmoModel = z.infer<typeof omoModelSchema>
45
+
46
+ const DISABLED_COMPONENTS = [
47
+ 'memory',
48
+ 'telemetry',
49
+ 'builtin-mcps',
50
+ 'onboarding',
51
+ 'lsp',
52
+ 'ast-grep',
53
+ 'browser-bridge',
54
+ 'computer-use',
55
+ 'x-search',
56
+ 'claude-code',
57
+ 'thread',
58
+ 'gateway',
59
+ 'config-watch',
60
+ ] as const
61
+
62
+ export function omoArguments(options: {
63
+ readonly model: string
64
+ readonly sessionId: string
65
+ readonly configDir: string
66
+ }): string[] {
67
+ return [
68
+ 'omo',
69
+ '-p',
70
+ '--mode',
71
+ 'json',
72
+ '--model',
73
+ `typeclaw/${options.model}`,
74
+ '--session-dir',
75
+ join(options.configDir, 'sessions'),
76
+ '--session-id',
77
+ options.sessionId,
78
+ '--no-approve',
79
+ '--offline',
80
+ '--permission-preset',
81
+ 'full-access',
82
+ '--no-ask-user',
83
+ '--no-model-fallback',
84
+ '--no-recommended-models',
85
+ ...DISABLED_COMPONENTS.map((name) => `--omo-senpi-${name}-disabled`),
86
+ ]
87
+ }
88
+
89
+ export function omoEnvironment(configDir: string, capability: string): Record<string, string> {
90
+ return {
91
+ HOME: join(configDir, 'home'),
92
+ OMO_CODING_AGENT_DIR: join(configDir, 'agent'),
93
+ TMPDIR: join(configDir, 'tmp'),
94
+ BUN_TMPDIR: join(configDir, 'tmp'),
95
+ BUN_INSTALL: join(configDir, 'home', '.bun'),
96
+ XDG_CONFIG_HOME: join(configDir, 'config'),
97
+ XDG_CACHE_HOME: join(configDir, 'cache'),
98
+ XDG_DATA_HOME: join(configDir, 'data'),
99
+ XDG_STATE_HOME: join(configDir, 'state'),
100
+ TYPECLAW_CODING_AGENT_CAPABILITY: capability,
101
+ PI_OFFLINE: '1',
102
+ PI_SKIP_VERSION_CHECK: '1',
103
+ PI_TELEMETRY: '0',
104
+ DO_NOT_TRACK: '1',
105
+ OMO_SEND_ANONYMOUS_TELEMETRY: '0',
106
+ SENPI_NO_FALLBACK: '1',
107
+ PI_CLAUDE_CODE_VERSION: CLAUDE_CODE_VERSION,
108
+ }
109
+ }
110
+
111
+ export function omoConfiguration(options: {
112
+ readonly configDir: string
113
+ readonly baseUrl: string
114
+ readonly provider: CodingAgentProvider
115
+ readonly model: OmoModel
116
+ }) {
117
+ const model = `typeclaw/${options.model.id}`
118
+ return {
119
+ models: {
120
+ providers: {
121
+ typeclaw: {
122
+ baseUrl: options.baseUrl + (options.provider === 'openai-codex' ? '/v1' : ''),
123
+ api: options.provider === 'anthropic' ? 'anthropic-messages' : 'openai-codex-responses',
124
+ apiKey: '$TYPECLAW_CODING_AGENT_CAPABILITY',
125
+ authHeader: true,
126
+ models: [options.model],
127
+ },
128
+ },
129
+ },
130
+ settings: {
131
+ enableInstallTelemetry: false,
132
+ transport: 'sse',
133
+ permissionPreset: 'full-access',
134
+ retry: { modelFallback: false },
135
+ compaction: { model },
136
+ enabledModels: [model],
137
+ disabledBuiltinExtensions: [
138
+ 'mcp',
139
+ 'cache-keepalive',
140
+ 'claude-sdk-oauth',
141
+ 'cursor-cli-oauth',
142
+ 'imagegen',
143
+ 'openai-image-gen',
144
+ 'anthropic-web-search',
145
+ 'openai-web-search',
146
+ 'look-at',
147
+ 'video-in',
148
+ 'btw',
149
+ 'schedule',
150
+ ],
151
+ },
152
+ orchestration: {
153
+ model_profile: model,
154
+ memory: { enabled: false },
155
+ telemetry: { enabled: false },
156
+ task: {
157
+ state_dir: join(options.configDir, 'task-state'),
158
+ default_execution_mode: 'in-process',
159
+ host_shard_prewarm: 'off',
160
+ default_concurrency: 3,
161
+ global_concurrency: 3,
162
+ max_depth: 1,
163
+ isolation: { enabled: false },
164
+ },
165
+ categories: Object.fromEntries(
166
+ [
167
+ 'visual-engineering',
168
+ 'artistry',
169
+ 'ultrabrain',
170
+ 'deep-low',
171
+ 'deep-high',
172
+ 'quick',
173
+ 'unspecified-low',
174
+ 'unspecified-high',
175
+ 'architect',
176
+ 'writing',
177
+ ].map((name) => [name, { models: [model] }]),
178
+ ),
179
+ agents: Object.fromEntries(
180
+ [
181
+ 'explore',
182
+ 'librarian',
183
+ 'plan-consultant',
184
+ 'plan-reviewer',
185
+ 'omo-native-code-reviewer',
186
+ 'omo-native-qa-executor',
187
+ 'omo-native-gate-reviewer',
188
+ ].map((name) => [name, { model, models: [], execution_mode: 'in-process' }]),
189
+ ),
190
+ },
191
+ }
192
+ }
@@ -0,0 +1,263 @@
1
+ import { spawn } from 'node:child_process'
2
+ import { once } from 'node:events'
3
+ import { join } from 'node:path'
4
+
5
+ import { readOomEvents, toolOomNote } from '@/container/oom-events'
6
+ import { withToolOomPriorityArgv } from '@/container/tool-oom-priority'
7
+ import { prepareCodingCommand } from '@/sandbox/coding-agent'
8
+ import type { CodingAgentAuthResolver, CodingAgentProvider } from '@/secrets/coding-agent-auth'
9
+
10
+ import { SecretScrubber, startCodingBroker, type CodingBroker } from './broker'
11
+ import { ClaudeStreamParser, claudeArguments, claudeEnvironment, type CodingMode } from './claude'
12
+ import { CodexStreamParser, codexArguments, codexConfig, codexEnvironment } from './codex'
13
+ import { omoArguments, omoConfiguration, omoEnvironment, type OmoModel } from './omo'
14
+ import { hasOmoSession, prepareOmoDirectories } from './omo-state'
15
+ import { OmoStreamParser } from './omo-stream'
16
+ import type { CodingWorkspace } from './worktree'
17
+
18
+ export type CodingRunResult = {
19
+ readonly state: 'completed' | 'incomplete' | 'failed' | 'cancelled'
20
+ readonly finalMessage: string
21
+ readonly sessionId?: string
22
+ readonly exitCode: number | null
23
+ readonly diagnostic: string
24
+ }
25
+
26
+ export type CodingRunOptions = {
27
+ readonly engine?: 'claude' | 'codex' | 'omo'
28
+ readonly provider?: CodingAgentProvider
29
+ readonly modelMetadata?: OmoModel
30
+ readonly workspace: CodingWorkspace
31
+ readonly auth: CodingAgentAuthResolver
32
+ readonly model: string
33
+ readonly allowedModels: readonly string[]
34
+ readonly mode: CodingMode
35
+ readonly sessionId: string
36
+ readonly resume: boolean
37
+ readonly prompt: string
38
+ readonly timeoutSeconds: number
39
+ readonly signal?: AbortSignal
40
+ readonly writeArtifact: (path: string, text: string) => Promise<void>
41
+ }
42
+
43
+ export async function runCodingAgent(
44
+ options: CodingRunOptions,
45
+ testDependencies?: {
46
+ command: (
47
+ argv: readonly string[],
48
+ env: Record<string, string>,
49
+ ) => Promise<{ argv: string[]; env: Record<string, string> }>
50
+ broker?: typeof startCodingBroker
51
+ },
52
+ ): Promise<CodingRunResult> {
53
+ const engine = options.engine ?? 'claude'
54
+ const deadline = Date.now() + options.timeoutSeconds * 1000
55
+ const timeout = new AbortController()
56
+ const signal = options.signal ? AbortSignal.any([options.signal, timeout.signal]) : timeout.signal
57
+ const timer = setTimeout(() => timeout.abort(), options.timeoutSeconds * 1000)
58
+ let broker: CodingBroker | undefined
59
+ let cleanupPrepared: (() => Promise<void>) | undefined
60
+ const cwd = join(options.workspace.taskRoot, 'worktree')
61
+ const parser =
62
+ engine === 'claude'
63
+ ? new ClaudeStreamParser()
64
+ : engine === 'codex'
65
+ ? new CodexStreamParser()
66
+ : new OmoStreamParser({ sessionId: options.sessionId, cwd })
67
+ let stdout = ''
68
+ let stdoutTail = ''
69
+ let stderr = ''
70
+ let exitCode: number | null = null
71
+ let failure = false
72
+ let missingSession = false
73
+ const oom = readOomEvents()
74
+ try {
75
+ signal.throwIfAborted()
76
+ const provider = options.provider ?? (engine === 'claude' ? 'anthropic' : 'openai-codex')
77
+ const configDir = join(options.workspace.taskRoot, engine)
78
+ if (engine === 'omo') {
79
+ if (!options.provider || options.modelMetadata?.id !== options.model)
80
+ throw new Error('Missing OmO model metadata.')
81
+ if (options.resume && !(await hasOmoSession(configDir, options.sessionId, cwd))) {
82
+ missingSession = true
83
+ throw new Error('OmO session is missing or unsafe.')
84
+ }
85
+ await prepareOmoDirectories(configDir)
86
+ }
87
+ broker = await (testDependencies?.broker ?? startCodingBroker)({
88
+ engine,
89
+ provider,
90
+ auth: options.auth,
91
+ allowedModels: options.allowedModels,
92
+ deadline,
93
+ signal,
94
+ })
95
+ if (engine === 'codex') {
96
+ await options.writeArtifact(join(configDir, 'config.toml'), codexConfig(options.model, broker.baseUrl))
97
+ }
98
+ if (engine === 'omo' && options.modelMetadata) {
99
+ const config = omoConfiguration({ configDir, baseUrl: broker.baseUrl, provider, model: options.modelMetadata })
100
+ for (const [path, value] of [
101
+ ['agent/models.json', config.models],
102
+ ['agent/settings.json', config.settings],
103
+ ['home/.omo/omo.jsonc', config.orchestration],
104
+ ] as const)
105
+ await options.writeArtifact(join(configDir, path), JSON.stringify(value, null, 2))
106
+ }
107
+ const env =
108
+ engine === 'claude'
109
+ ? claudeEnvironment(configDir, broker.baseUrl, broker.capability)
110
+ : engine === 'codex'
111
+ ? codexEnvironment(configDir, broker.capability)
112
+ : omoEnvironment(configDir, broker.capability)
113
+ const args =
114
+ engine === 'claude'
115
+ ? claudeArguments(options)
116
+ : engine === 'codex'
117
+ ? codexArguments(options)
118
+ : omoArguments({ ...options, configDir })
119
+ const prepared: {
120
+ argv: string[]
121
+ env: Record<string, string>
122
+ extraFiles?: Array<number | 'ignore'>
123
+ cleanup?: () => Promise<void>
124
+ } = testDependencies
125
+ ? await testDependencies.command(args, env)
126
+ : await prepareCodingCommand(args, {
127
+ source: options.workspace.source,
128
+ taskRoot: options.workspace.taskRoot,
129
+ cwd,
130
+ mode: options.mode,
131
+ env,
132
+ engine,
133
+ }).then((command) => ({
134
+ argv: ['bash', '-c', `exec ${command.commandString}`],
135
+ env: command.spawnEnv,
136
+ extraFiles: command.extraFiles,
137
+ cleanup: command.cleanup,
138
+ }))
139
+ cleanupPrepared = prepared.cleanup
140
+ signal.throwIfAborted()
141
+ const [executable, ...argv] = withToolOomPriorityArgv(prepared.argv)
142
+ if (!executable) throw new Error('Coding command is empty.')
143
+ const child = spawn(executable, argv, {
144
+ cwd,
145
+ env: prepared.env,
146
+ detached: true,
147
+ stdio: ['pipe', 'pipe', 'pipe', ...(prepared.extraFiles ?? [])],
148
+ })
149
+ if (!child.stdin || !child.stdout || !child.stderr) throw new Error('Coding pipes unavailable.')
150
+ const kill = () => {
151
+ if (child.pid === undefined) return
152
+ try {
153
+ process.kill(-child.pid, 'SIGKILL')
154
+ } catch (error) {
155
+ if (!(error instanceof Error && 'code' in error && error.code === 'ESRCH')) throw error
156
+ }
157
+ }
158
+ const closed = once(child, 'close')
159
+ // Attach readers before sending the prompt or cancellation.
160
+ const consume = async (stream: NodeJS.ReadableStream, output: boolean): Promise<void> => {
161
+ const decoder = new TextDecoder()
162
+ const scrubber = new SecretScrubber([broker?.capability ?? ''])
163
+ let total = 0
164
+ for await (const chunk of stream) {
165
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))
166
+ total += bytes.length
167
+ if (total > 16 * 1024 * 1024) {
168
+ failure = true
169
+ kill()
170
+ continue
171
+ }
172
+ const text = scrubber.push(decoder.decode(bytes, { stream: true }))
173
+ if (output) {
174
+ stdout += text
175
+ try {
176
+ parser.push(text)
177
+ } catch {
178
+ failure = true
179
+ kill()
180
+ }
181
+ } else stderr += text
182
+ }
183
+ const final = scrubber.push(decoder.decode(), true)
184
+ if (output) {
185
+ stdout += final
186
+ stdoutTail = final
187
+ } else stderr += final
188
+ }
189
+ // Observe pipe/parser failures immediately, including the decoder's final
190
+ // flush. Waiting for process exit before attaching a rejection handler can
191
+ // leave an oversized final JSONL record as an unhandled rejection.
192
+ const reads = [consume(child.stdout, true), consume(child.stderr, false)].map((read) =>
193
+ read.catch(() => {
194
+ failure = true
195
+ kill()
196
+ }),
197
+ )
198
+ signal.addEventListener('abort', kill, { once: true })
199
+ child.stdin.on('error', () => {
200
+ failure = true
201
+ })
202
+ try {
203
+ if (signal.aborted) kill()
204
+ else
205
+ child.stdin.end(
206
+ engine !== 'claude' && options.mode === 'plan'
207
+ ? `Plan this task without modifying the repository. The worktree and Git database are read-only.\n\n${options.prompt}`
208
+ : options.prompt,
209
+ )
210
+ const [code, killedBy] = await closed
211
+ exitCode = typeof code === 'number' ? code : killedBy === 'SIGKILL' ? 137 : null
212
+ await Promise.all(reads)
213
+ // The decoder/scrubber tail is available only at EOF. Validate it after
214
+ // reaping, rather than attempting to kill a process already exiting.
215
+ parser.push(stdoutTail)
216
+ parser.finish()
217
+ } finally {
218
+ signal.removeEventListener('abort', kill)
219
+ kill()
220
+ await Promise.allSettled([closed, ...reads])
221
+ }
222
+ } catch {
223
+ failure = true
224
+ } finally {
225
+ clearTimeout(timer)
226
+ await broker?.close()
227
+ await cleanupPrepared?.()
228
+ }
229
+ const invocation = crypto.randomUUID()
230
+ await options.writeArtifact(join(options.workspace.taskRoot, 'output', `${invocation}.jsonl`), stdout)
231
+ await options.writeArtifact(join(options.workspace.taskRoot, 'output', `${invocation}.stderr`), stderr)
232
+ const timedOut =
233
+ timeout.signal.aborted ||
234
+ (options.signal?.reason instanceof DOMException && options.signal.reason.name === 'TimeoutError')
235
+ const state = timedOut
236
+ ? 'incomplete'
237
+ : options.signal?.aborted
238
+ ? 'cancelled'
239
+ : missingSession
240
+ ? 'incomplete'
241
+ : failure || exitCode !== 0 || parser.failed || parser.malformed
242
+ ? 'failed'
243
+ : !parser.terminal || parser.permissionDenied || (engine !== 'claude' && !parser.sessionId)
244
+ ? 'incomplete'
245
+ : 'completed'
246
+ return {
247
+ state,
248
+ finalMessage: parser.finalMessage,
249
+ exitCode,
250
+ ...(parser.sessionId ? { sessionId: parser.sessionId } : {}),
251
+ diagnostic:
252
+ toolOomNote(oom, exitCode ?? 0, 'coding_agent') ??
253
+ (state === 'completed'
254
+ ? ''
255
+ : missingSession
256
+ ? 'The recorded OmO session is missing or unsafe. Restore its task-local session file before resuming; partial work is preserved.'
257
+ : timedOut
258
+ ? 'Invocation timed out; partial work is preserved.'
259
+ : parser.permissionDenied
260
+ ? 'The coding CLI reported a permission denial; review the task and continue explicitly.'
261
+ : 'Invocation did not complete. Inspect the saved output and partial diff; verify the installed CLI and sandbox.'),
262
+ }
263
+ }
@@ -0,0 +1,62 @@
1
+ import { Type } from '@earendil-works/pi-ai'
2
+ import { defineTool } from '@earendil-works/pi-coding-agent'
3
+
4
+ import type { SessionOrigin } from '@/agent/session-origin'
5
+ import type { PermissionService } from '@/permissions'
6
+
7
+ import { codingRequestSchema, getCodingAgentService, type CodingAgentService } from './index'
8
+
9
+ export function createCodingAgentTool(options: {
10
+ agentDir: string
11
+ sessionId: string
12
+ getOrigin: () => SessionOrigin | undefined
13
+ permissions: PermissionService
14
+ service?: CodingAgentService
15
+ }) {
16
+ return defineTool({
17
+ name: 'coding_agent',
18
+ label: 'Coding Agent',
19
+ description:
20
+ 'Run headless Claude Code, Codex or OmO in an isolated persistent Git worktree through the credential broker. ' +
21
+ 'Use a background operator for long runs. New tasks require repo and an anthropic (claude/omo) or openai-codex (codex/omo) modelRef; continuation uses taskId. ' +
22
+ 'The baseline is committed HEAD, not dirty source files. Inspect state, finalMessage and the complete patch before applying. ' +
23
+ 'Plan mode makes the worktree and Git database read-only. result reads a receipt; dispose requires explicit discard:true.',
24
+ parameters: Type.Union([
25
+ Type.Object({
26
+ action: Type.Literal('run'),
27
+ engine: Type.Union([Type.Literal('claude'), Type.Literal('codex'), Type.Literal('omo')]),
28
+ repo: Type.Optional(Type.String()),
29
+ modelRef: Type.Optional(Type.String()),
30
+ taskId: Type.Optional(Type.String()),
31
+ prompt: Type.String(),
32
+ mode: Type.Optional(Type.Union([Type.Literal('plan'), Type.Literal('code')])),
33
+ timeoutSeconds: Type.Optional(Type.Number({ exclusiveMinimum: 0, maximum: 2_147_483.647 })),
34
+ }),
35
+ Type.Object({ action: Type.Literal('result'), taskId: Type.String() }),
36
+ Type.Object({ action: Type.Literal('dispose'), taskId: Type.String(), discard: Type.Literal(true) }),
37
+ ]),
38
+ async execute(_id, params, signal, onUpdate) {
39
+ try {
40
+ const request = codingRequestSchema.parse(params)
41
+ const result = await (options.service ?? getCodingAgentService(options.agentDir)).execute(
42
+ request,
43
+ {
44
+ sessionId: options.sessionId,
45
+ origin: options.getOrigin(),
46
+ permissions: options.permissions,
47
+ onPrepared: (receipt) =>
48
+ onUpdate?.({
49
+ content: [{ type: 'text', text: JSON.stringify(receipt) }],
50
+ details: receipt,
51
+ }),
52
+ },
53
+ signal,
54
+ )
55
+ return { content: [{ type: 'text' as const, text: JSON.stringify(result) }], details: result }
56
+ } catch (error) {
57
+ const result = { ok: false, diagnostic: error instanceof Error ? error.message : 'Coding delegation failed.' }
58
+ return { content: [{ type: 'text' as const, text: JSON.stringify(result) }], details: result }
59
+ }
60
+ },
61
+ })
62
+ }