@zergai/ztc 0.19.0-beta.1 → 0.20.0-beta.1

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 (196) hide show
  1. package/README.md +222 -6
  2. package/bin/zmux-darwin-arm64 +0 -0
  3. package/bin/ztc-audio-darwin-arm64 +0 -0
  4. package/bin/ztc-capture-darwin-arm64 +0 -0
  5. package/bin/ztc-tui-darwin-arm64 +0 -0
  6. package/bin/zterm-darwin-arm64 +2 -2
  7. package/dist/agent/agent.d.ts +17 -0
  8. package/dist/agent/agent.js +77 -4
  9. package/dist/agent/backends/index.js +5 -3
  10. package/dist/agent/backends/zrouter_stream.js +8 -4
  11. package/dist/agent/commands/goal.d.ts +2 -0
  12. package/dist/agent/commands/goal.js +7 -2
  13. package/dist/agent/factory.d.ts +2 -0
  14. package/dist/agent/factory.js +1 -0
  15. package/dist/agent/request_encoder.d.ts +2 -1
  16. package/dist/agent/request_encoder.js +4 -3
  17. package/dist/agent/runtime/policy.d.ts +1 -0
  18. package/dist/agent/runtime/policy.js +23 -3
  19. package/dist/agent/runtime/tool_runtime.js +13 -12
  20. package/dist/agent/subagent.js +2 -1
  21. package/dist/agent/tools/ask_user.d.ts +1 -1
  22. package/dist/agent/tools/ask_user.js +15 -8
  23. package/dist/agent/tools/pane.d.ts +6 -0
  24. package/dist/agent/tools/pane.js +18 -4
  25. package/dist/agent/tools/search.js +1 -1
  26. package/dist/agent/tools/sim_domain_tools.d.ts +4 -0
  27. package/dist/agent/tools/sim_domain_tools.js +28 -2
  28. package/dist/agent/tools/types.d.ts +3 -0
  29. package/dist/app/correlated_turn.d.ts +14 -0
  30. package/dist/app/correlated_turn.js +78 -0
  31. package/dist/app/prompt_turn.d.ts +2 -1
  32. package/dist/app/prompt_turn.js +15 -2
  33. package/dist/app/session_manager.d.ts +17 -11
  34. package/dist/app/session_manager.js +74 -30
  35. package/dist/app/tool_callbacks.d.ts +1 -1
  36. package/dist/app/workspace_layout_controller.d.ts +21 -2
  37. package/dist/app/workspace_layout_controller.js +61 -10
  38. package/dist/app/workspace_monitor.js +67 -7
  39. package/dist/app/workspace_presets.d.ts +1 -0
  40. package/dist/app/workspace_presets.js +2 -2
  41. package/dist/cli.js +6 -2
  42. package/dist/cli_args.js +1 -0
  43. package/dist/cli_main.js +48 -2
  44. package/dist/cli_ratatui.d.ts +56 -8
  45. package/dist/cli_ratatui.js +689 -109
  46. package/dist/config/permissions.js +1 -1
  47. package/dist/config/router_required.d.ts +11 -0
  48. package/dist/config/router_required.js +23 -0
  49. package/dist/config/types.d.ts +5 -0
  50. package/dist/config.d.ts +3 -1
  51. package/dist/config.js +66 -49
  52. package/dist/desktop/daily/broker.d.ts +26 -0
  53. package/dist/desktop/daily/broker.js +140 -0
  54. package/dist/desktop/daily/codex_config.d.ts +2 -0
  55. package/dist/desktop/daily/codex_config.js +119 -0
  56. package/dist/desktop/daily/codex_exec_adapter.d.ts +42 -0
  57. package/dist/desktop/daily/codex_exec_adapter.js +251 -0
  58. package/dist/desktop/daily/control_client.d.ts +4 -0
  59. package/dist/desktop/daily/control_client.js +214 -0
  60. package/dist/desktop/daily/control_credentials.d.ts +15 -0
  61. package/dist/desktop/daily/control_credentials.js +85 -0
  62. package/dist/desktop/daily/control_hello.d.ts +10 -0
  63. package/dist/desktop/daily/control_hello.js +6 -0
  64. package/dist/desktop/daily/control_protocol.d.ts +39 -0
  65. package/dist/desktop/daily/control_protocol.js +4 -0
  66. package/dist/desktop/daily/control_schema.d.ts +9 -0
  67. package/dist/desktop/daily/control_schema.js +25 -0
  68. package/dist/desktop/daily/control_server.d.ts +44 -0
  69. package/dist/desktop/daily/control_server.js +286 -0
  70. package/dist/desktop/daily/daily_store.d.ts +71 -0
  71. package/dist/desktop/daily/daily_store.js +290 -0
  72. package/dist/desktop/daily/delegated_ztc_contract.d.ts +37 -0
  73. package/dist/desktop/daily/delegated_ztc_contract.js +90 -0
  74. package/dist/desktop/daily/desktop_wiring.d.ts +112 -0
  75. package/dist/desktop/daily/desktop_wiring.js +1048 -0
  76. package/dist/desktop/daily/enrollment.d.ts +74 -0
  77. package/dist/desktop/daily/enrollment.js +77 -0
  78. package/dist/desktop/daily/file_facts.d.ts +2 -0
  79. package/dist/desktop/daily/file_facts.js +41 -0
  80. package/dist/desktop/daily/lease.d.ts +57 -0
  81. package/dist/desktop/daily/lease.js +332 -0
  82. package/dist/desktop/daily/legacy_codex_homes.d.ts +1 -0
  83. package/dist/desktop/daily/legacy_codex_homes.js +26 -0
  84. package/dist/desktop/daily/native_pane_launcher.d.ts +31 -0
  85. package/dist/desktop/daily/native_pane_launcher.js +226 -0
  86. package/dist/desktop/daily/native_records.d.ts +13 -0
  87. package/dist/desktop/daily/native_records.js +81 -0
  88. package/dist/desktop/daily/native_status.d.ts +4 -0
  89. package/dist/desktop/daily/native_status.js +28 -0
  90. package/dist/desktop/daily/native_tool.d.ts +134 -0
  91. package/dist/desktop/daily/native_tool.js +91 -0
  92. package/dist/desktop/daily/owner_files.d.ts +3 -0
  93. package/dist/desktop/daily/owner_files.js +88 -0
  94. package/dist/desktop/daily/owner_seals.d.ts +9 -0
  95. package/dist/desktop/daily/owner_seals.js +56 -0
  96. package/dist/desktop/daily/process_identity.d.ts +13 -0
  97. package/dist/desktop/daily/process_identity.js +137 -0
  98. package/dist/desktop/daily/profile_bootstrap.d.ts +60 -0
  99. package/dist/desktop/daily/profile_bootstrap.js +194 -0
  100. package/dist/desktop/daily/raw_receipts.d.ts +1 -0
  101. package/dist/desktop/daily/raw_receipts.js +18 -0
  102. package/dist/desktop/daily/recipes.d.ts +36 -0
  103. package/dist/desktop/daily/recipes.js +177 -0
  104. package/dist/desktop/daily/router_state.d.ts +33 -0
  105. package/dist/desktop/daily/router_state.js +39 -0
  106. package/dist/desktop/daily/schema_registry.d.ts +19 -0
  107. package/dist/desktop/daily/schema_registry.js +71 -0
  108. package/dist/desktop/daily/source_baseline.d.ts +13 -0
  109. package/dist/desktop/daily/source_baseline.js +44 -0
  110. package/dist/desktop/daily/status_restore.d.ts +9 -0
  111. package/dist/desktop/daily/status_restore.js +114 -0
  112. package/dist/desktop/daily/summary.d.ts +59 -0
  113. package/dist/desktop/daily/summary.js +75 -0
  114. package/dist/desktop/daily/worker_provenance.d.ts +2 -0
  115. package/dist/desktop/daily/worker_provenance.js +18 -0
  116. package/dist/desktop/daily/worker_stop.d.ts +2 -0
  117. package/dist/desktop/daily/worker_stop.js +26 -0
  118. package/dist/desktop/daily/ztc_headless_adapter.d.ts +40 -0
  119. package/dist/desktop/daily/ztc_headless_adapter.js +194 -0
  120. package/dist/domain.d.ts +1 -1
  121. package/dist/domain.js +1 -1
  122. package/dist/events.d.ts +23 -1
  123. package/dist/headless.d.ts +9 -0
  124. package/dist/headless.js +161 -26
  125. package/dist/headless_approval.d.ts +29 -0
  126. package/dist/headless_approval.js +69 -0
  127. package/dist/headless_cli.js +2 -0
  128. package/dist/headless_cli_args.d.ts +4 -0
  129. package/dist/headless_cli_args.js +5 -0
  130. package/dist/library.d.ts +20 -0
  131. package/dist/library.js +66 -12
  132. package/dist/mcp/client.d.ts +16 -1
  133. package/dist/mcp/client.js +11 -5
  134. package/dist/mcp/registry.d.ts +3 -1
  135. package/dist/mcp/registry.js +10 -1
  136. package/dist/panes/pane_registry.js +14 -3
  137. package/dist/panes/types.d.ts +7 -1
  138. package/dist/panes/ztc_launch.d.ts +5 -0
  139. package/dist/panes/ztc_launch.js +30 -14
  140. package/dist/session.d.ts +6 -3
  141. package/dist/session.js +21 -2
  142. package/dist/simulation/domain_types.d.ts +2 -0
  143. package/dist/simulation/domains/loader.d.ts +7 -1
  144. package/dist/simulation/domains/loader.js +33 -1
  145. package/dist/simulation/living/context.d.ts +19 -19
  146. package/dist/simulation/living/definition.d.ts +2 -2
  147. package/dist/simulation/living/frame.d.ts +1 -1
  148. package/dist/simulation/living/open-world.d.ts +3 -3
  149. package/dist/simulation/living/types.d.ts +24 -24
  150. package/dist/simulation/toolkit/dynamic_state.d.ts +1 -1
  151. package/dist/skills/bundled/init-context/SKILL.md +16 -0
  152. package/dist/skills/registry.js +7 -3
  153. package/dist/tools.d.ts +6 -0
  154. package/dist/tools.js +14 -0
  155. package/dist/types.d.ts +30 -0
  156. package/dist/ui/ratatui/mux_persistence.d.ts +3 -1
  157. package/dist/ui/ratatui/mux_persistence.js +9 -2
  158. package/dist/ui/ratatui/pane_credential_broker.d.ts +8 -4
  159. package/dist/ui/ratatui/pane_credential_broker.js +26 -11
  160. package/dist/ui/ratatui/pane_relay.d.ts +2 -0
  161. package/dist/ui/ratatui/process.d.ts +6 -0
  162. package/dist/ui/ratatui/process.js +104 -6
  163. package/dist/ui/ratatui/protocol.d.ts +13 -0
  164. package/dist/ui/ratatui/protocol.js +1 -0
  165. package/dist/utils/compaction.js +6 -4
  166. package/dist/utils/subprocess_env.js +2 -0
  167. package/dist/web/browser_events.d.ts +10 -0
  168. package/dist/web/browser_events.js +9 -0
  169. package/dist/web/mirror_stream.d.ts +17 -5
  170. package/dist/web/mirror_stream.js +105 -13
  171. package/dist/web/pane_credentials.d.ts +6 -3
  172. package/dist/web/pane_credentials.js +20 -12
  173. package/dist/web/pane_registry.js +1 -0
  174. package/dist/workspace_agent.d.ts +2 -1
  175. package/dist/workspace_agent.js +7 -1
  176. package/dist/workspace_collision.d.ts +3 -0
  177. package/dist/workspace_collision.js +1 -1
  178. package/dist/workspace_layout.d.ts +3 -2
  179. package/dist/workspace_layout.js +8 -2
  180. package/dist/workspace_runtime.d.ts +7 -1
  181. package/dist/workspace_runtime.js +3 -3
  182. package/dist/zerg/manifest_builder_tools.js +35 -4
  183. package/dist/zerg/manifest_validator.js +55 -0
  184. package/dist/zlm-embed.mjs +261 -116
  185. package/node_modules/@zerg/model-contracts/README.md +19 -0
  186. package/node_modules/@zerg/model-contracts/index.js +19 -1
  187. package/node_modules/@ztc/sim-graph/dist/index.d.ts +1 -0
  188. package/node_modules/@ztc/sim-graph/dist/index.js +1 -0
  189. package/node_modules/@ztc/sim-graph/dist/sim_graph.d.ts +351 -0
  190. package/node_modules/@ztc/sim-graph/dist/sim_graph.js +795 -0
  191. package/node_modules/@ztc/sim-graph/package.json +37 -0
  192. package/node_modules/@ztc/sim-graph/src/index.ts +1 -0
  193. package/node_modules/@ztc/sim-graph/src/sim_graph.ts +1305 -0
  194. package/package.json +25 -24
  195. package/packages/model-contracts/README.md +19 -0
  196. package/packages/model-contracts/index.js +19 -1
@@ -0,0 +1,251 @@
1
+ import { prepareRawReceipt } from './raw_receipts.js';
2
+ import { observeSource, sourceChanged } from './source_baseline.js';
3
+ import { bindWorkerProvenance } from './worker_provenance.js';
4
+ import { atomicOwnerFile } from './owner_files.js';
5
+ import { readCodexCredentialStore } from './codex_config.js';
6
+ import { terminateWorker } from './worker_stop.js';
7
+ import { execFile, spawn } from 'node:child_process';
8
+ import { constants } from 'node:fs';
9
+ import { access, appendFile, lstat, mkdir, open, realpath } from 'node:fs/promises';
10
+ import { dirname, delimiter, isAbsolute, join } from 'node:path';
11
+ import { StringDecoder } from 'node:string_decoder';
12
+ import { promisify } from 'node:util';
13
+ import { z } from 'zod';
14
+ import { assertSettingsAllowed, buildLaunchArgv, buildResumeArgv, recipeFor } from './recipes.js';
15
+ import { policyHash } from './native_tool.js';
16
+ import { assignSummaryPaths } from './summary.js';
17
+ import { project, writeSchemaFile } from './schema_registry.js';
18
+ import { groupMembersOf, observeProcessStart, processGroupOf } from './process_identity.js';
19
+ const exec = promisify(execFile);
20
+ const count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
21
+ const itemTypes = ['command_execution', 'agent_message', 'reasoning', 'file_change', 'mcp_tool_call', 'web_search', 'todo_list', 'collab_tool_call'];
22
+ const itemSchema = z.object({ id: z.string().min(1).max(256), type: z.enum(itemTypes),
23
+ status: z.enum(['in_progress', 'completed', 'failed']).optional(), exit_code: z.number().int().nullable().optional() });
24
+ const eventSchema = z.object({ type: z.string() });
25
+ const threadSchema = z.object({ thread_id: z.uuid() });
26
+ const usageSchema = z.object({ usage: z.object({ input_tokens: count, output_tokens: count, cached_input_tokens: count.optional(),
27
+ cache_write_input_tokens: count.optional(), reasoning_output_tokens: count.optional() }) });
28
+ function environment(parent) {
29
+ const keys = ['PATH', 'HOME', 'USER', 'LOGNAME', 'SHELL', 'TMPDIR', 'TMP', 'TEMP', 'LANG', 'LC_ALL', 'TZ', 'TERM', 'CI', 'NO_COLOR', 'CODEX_HOME'];
30
+ return Object.fromEntries(keys.filter(key => parent[key] !== undefined).map(key => [key, parent[key]]));
31
+ }
32
+ async function cliIdentity(command, env) {
33
+ let path = null;
34
+ for (const candidate of isAbsolute(command) ? [command] : (env.PATH ?? '').split(delimiter).map(root => join(root, command))) {
35
+ try {
36
+ await access(candidate, constants.X_OK);
37
+ path = await realpath(candidate);
38
+ break;
39
+ }
40
+ catch { }
41
+ }
42
+ if (path === null)
43
+ throw new Error('Codex CLI unavailable');
44
+ const { stdout } = await exec(path, ['--version'], { env, timeout: 5000, maxBuffer: 1024 });
45
+ const match = /^codex-cli (\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?)\s*$/.exec(stdout);
46
+ if (!match)
47
+ throw new Error('Codex CLI version unsupported');
48
+ return { path, version: match[1] };
49
+ }
50
+ async function readSink(path) {
51
+ const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
52
+ try {
53
+ const metadata = await file.stat();
54
+ if (!metadata.isFile() || metadata.nlink !== 1 || metadata.uid !== process.getuid?.() || metadata.size > 65536)
55
+ return Buffer.alloc(0);
56
+ const bytes = Buffer.alloc(65537);
57
+ const result = await file.read(bytes, 0, bytes.length, 0);
58
+ return result.bytesRead > 65536 ? Buffer.alloc(0) : bytes.subarray(0, result.bytesRead);
59
+ }
60
+ finally {
61
+ await file.close();
62
+ }
63
+ }
64
+ export async function runCodexExec(record, options) {
65
+ assertSettingsAllowed(record.launch.args);
66
+ if (record.launch.tool !== 'codex' || record.launch.mode !== 'delegated')
67
+ throw new Error('Delegated Codex record required');
68
+ if (!record.launch.policy?.outputSink)
69
+ throw new Error('Codex output sink required');
70
+ if (record.launch.policy.capabilities.shell_exec !== true)
71
+ throw new Error('Codex shell capability is required');
72
+ await mkdir(dirname(record.launch.policy.outputSink), { recursive: true, mode: 0o700 });
73
+ const paths = await assignSummaryPaths(record.launch.worktree.repositoryRoot, record.launch.policy.outputSink);
74
+ const artifactPath = paths.resultPath;
75
+ const env = environment(options.env ?? process.env);
76
+ const cli = await cliIdentity(options.command ?? record.launch.command, env);
77
+ if (options.resume && (cli.path !== record.launch.command || cli.version !== record.launch.cliVersion))
78
+ throw new Error('Codex CLI identity changed');
79
+ const recipe = recipeFor('codex', 'delegated', cli.version);
80
+ if ('unsupported' in recipe)
81
+ throw new Error('Codex CLI version unsupported');
82
+ record.launch.cliVersion = cli.version;
83
+ if (options.resume)
84
+ buildResumeArgv(record, options.prompt);
85
+ else
86
+ buildLaunchArgv(record);
87
+ const schema = await writeSchemaFile('fixture-count-v1', dirname(artifactPath));
88
+ record.launch.command = cli.path;
89
+ record.launch.cliVersion = cli.version;
90
+ record.launch.versionRange = recipe.versionRange;
91
+ record.launch.args = ['--output-schema', schema.path];
92
+ record.launch.policy.outputSink = artifactPath;
93
+ record.launch.policy.schemaId = 'fixture-count-v1';
94
+ record.launch.policy.schemaHash = schema.hash;
95
+ record.launch.policy.policyHash = policyHash(record.launch.policy);
96
+ const codexProjectRoots = await Promise.all([realpath(record.launch.cwd), realpath(record.launch.worktree.repositoryRoot), realpath(dirname(record.launch.worktree.gitCommonDir))]);
97
+ const commandRecord = { ...record, codexProjectRoots, codexCredentialStore: await readCodexCredentialStore(env), launch: { ...record.launch, cwd: codexProjectRoots[0] } };
98
+ const args = options.resume ? buildResumeArgv(commandRecord, options.prompt) : buildLaunchArgv(commandRecord);
99
+ const expectedId = options.resume ? record.identity.canonicalId : null;
100
+ if (!options.resume)
101
+ record.identity = { canonicalId: null, state: 'unbound', source: 'none', validatedAt: null };
102
+ await atomicOwnerFile(artifactPath, '');
103
+ const result = { baselineDirty: false, state: 'running', approvalState: 'none', errorClass: 'none', eventCount: 0, unclassified: 0,
104
+ tokens: { input: 0, output: 0 }, cachedInput: 0, reasoningOutput: 0,
105
+ items: Object.fromEntries(itemTypes.map(type => [type, 0])),
106
+ projection: { ok: false, reason: 'empty_sink' }, effectObserved: false };
107
+ let stopping = null;
108
+ let halt = () => { };
109
+ let completed = false;
110
+ let failedCommand = false;
111
+ let mismatched = false;
112
+ let callbackFailed = false;
113
+ const publish = () => {
114
+ try {
115
+ options.onUpdate?.(structuredClone(record), structuredClone(result));
116
+ }
117
+ catch {
118
+ callbackFailed = true;
119
+ result.errorClass = 'adapter';
120
+ }
121
+ };
122
+ const unknown = () => { result.unclassified++; result.state = 'approval_pending'; result.approvalState = 'denied'; };
123
+ const consume = (line) => {
124
+ if (mismatched || !line.trim())
125
+ return;
126
+ options.onRawLines?.([line.slice(0, 4096)]);
127
+ result.eventCount++;
128
+ let value;
129
+ try {
130
+ value = JSON.parse(line);
131
+ }
132
+ catch {
133
+ unknown();
134
+ publish();
135
+ return;
136
+ }
137
+ const event = eventSchema.safeParse(value);
138
+ if (!event.success) {
139
+ unknown();
140
+ publish();
141
+ return;
142
+ }
143
+ if (event.data.type === 'thread.started') {
144
+ const thread = threadSchema.safeParse(value);
145
+ if (!thread.success)
146
+ unknown();
147
+ else if (expectedId !== null && thread.data.thread_id !== expectedId
148
+ || record.identity.canonicalId !== null && record.identity.canonicalId !== thread.data.thread_id) {
149
+ mismatched = true;
150
+ record.identity.state = 'mismatched';
151
+ result.errorClass = 'identity_mismatch';
152
+ halt();
153
+ }
154
+ else
155
+ record.identity = { canonicalId: thread.data.thread_id, state: 'bound', source: 'tool_reported', validatedAt: Date.now() };
156
+ }
157
+ else if (event.data.type === 'turn.started') { }
158
+ else if (event.data.type === 'item.started' || event.data.type === 'item.completed') {
159
+ const parsed = z.object({ item: itemSchema }).safeParse(value);
160
+ if (!parsed.success)
161
+ unknown();
162
+ else {
163
+ const item = parsed.data.item;
164
+ result.items[item.type]++;
165
+ if (item.type === 'mcp_tool_call' || item.type === 'web_search' || item.type === 'collab_tool_call')
166
+ unknown();
167
+ if (item.type === 'command_execution' && event.data.type === 'item.completed' && item.status === 'failed')
168
+ failedCommand = true;
169
+ }
170
+ }
171
+ else if (event.data.type === 'turn.completed') {
172
+ const parsed = usageSchema.safeParse(value);
173
+ if (!parsed.success)
174
+ unknown();
175
+ else {
176
+ completed = true;
177
+ result.tokens.input += parsed.data.usage.input_tokens;
178
+ result.tokens.output += parsed.data.usage.output_tokens;
179
+ result.cachedInput += parsed.data.usage.cached_input_tokens ?? 0;
180
+ result.reasoningOutput += parsed.data.usage.reasoning_output_tokens ?? 0;
181
+ }
182
+ }
183
+ else
184
+ unknown();
185
+ publish();
186
+ };
187
+ if (options.rawEventPath)
188
+ await prepareRawReceipt(options.rawEventPath);
189
+ const baseline = options.sourceTreeChanged ? null : await observeSource(record.launch.cwd);
190
+ result.baselineDirty = baseline?.dirty ?? false;
191
+ if (options.beforeSpawn?.() === false)
192
+ throw new Error('Native launch cancelled');
193
+ const child = spawn(cli.path, args, { cwd: record.launch.cwd, env, detached: true, stdio: ['ignore', 'pipe', 'pipe'],
194
+ timeout: options.timeoutMs ?? 180000, killSignal: 'SIGINT' });
195
+ halt = () => { stopping ??= terminateWorker(child); };
196
+ const closed = new Promise(resolve => {
197
+ child.once('error', () => { result.errorClass = 'launch_refused'; });
198
+ child.once('close', (code, signal) => resolve({ code, signal }));
199
+ });
200
+ const decoder = new StringDecoder('utf8');
201
+ let pending = '';
202
+ let raw = Promise.resolve();
203
+ child.stdout.on('data', (bytes) => {
204
+ if (options.rawEventPath)
205
+ raw = raw.then(() => appendFile(options.rawEventPath, bytes));
206
+ pending += decoder.write(bytes);
207
+ if (Buffer.byteLength(pending) > 1024 * 1024) {
208
+ pending = '';
209
+ unknown();
210
+ return;
211
+ }
212
+ const lines = pending.split('\n');
213
+ pending = lines.pop();
214
+ for (const line of lines)
215
+ consume(line);
216
+ });
217
+ child.stderr.on('data', (bytes) => { options.onRawLines?.(bytes.toString('utf8').split('\n').filter(Boolean).slice(-500).map(line => line.slice(0, 4096))); });
218
+ if (child.pid !== undefined) {
219
+ const [start, group] = await Promise.all([observeProcessStart(child.pid), processGroupOf(child.pid)]);
220
+ if (start !== null && group !== null) {
221
+ record.process = { leaderPid: child.pid, leaderStartMs: start, pgid: group,
222
+ paneId: record.paneId, desktopOwnerId: options.owner.desktopOwnerId, revision: options.owner.revision };
223
+ await bindWorkerProvenance(record, dirname(artifactPath));
224
+ publish();
225
+ }
226
+ }
227
+ const exit = await closed;
228
+ await stopping;
229
+ await raw;
230
+ pending += decoder.end();
231
+ if (pending)
232
+ consume(pending);
233
+ record.outcome = { exit, stopState: 'leader_exited', survivors: record.process === null ? [] : await groupMembersOf(record.process.pgid) ?? [], containment: 'unverified' };
234
+ const changed = options.sourceTreeChanged ? await options.sourceTreeChanged() : await sourceChanged(baseline);
235
+ for (const path of options.effectPaths ?? []) {
236
+ if (await lstat(path).then(() => true).catch((error) => { if (error.code === 'ENOENT')
237
+ return false; throw error; }))
238
+ result.effectObserved = true;
239
+ }
240
+ result.projection = project('fixture-count-v1', schema.hash, await readSink(artifactPath).catch(() => Buffer.alloc(0)), exit.code, changed || result.effectObserved);
241
+ result.state = mismatched ? 'failed' : result.unclassified > 0 ? 'approval_pending' : callbackFailed || !completed || record.identity.state !== 'bound' || exit.code !== 0 || result.effectObserved ? 'failed'
242
+ : options.writeIntent && failedCommand ? 'approval_denied' : options.writeIntent ? 'failed' : result.projection.ok ? 'result_available' : 'result_rejected';
243
+ if (mismatched)
244
+ record.identity.state = 'mismatched';
245
+ if (result.state === 'approval_denied')
246
+ result.approvalState = 'denied';
247
+ if (exit.code !== 0 && result.errorClass === 'none')
248
+ result.errorClass = 'exited_nonzero';
249
+ publish();
250
+ return result;
251
+ }
@@ -0,0 +1,4 @@
1
+ export declare function runDesktopCommand(args: string[], options?: {
2
+ env?: NodeJS.ProcessEnv;
3
+ output?: (text: string) => void;
4
+ }): Promise<number>;
@@ -0,0 +1,214 @@
1
+ import { createHash, createPublicKey, randomBytes, verify as verifySignature } from 'node:crypto';
2
+ import { helloMessage, helloResponseSchema } from './control_hello.js';
3
+ import { DailyError } from './control_protocol.js';
4
+ import { execFile } from 'node:child_process';
5
+ import { promisify } from 'node:util';
6
+ import { observeProcessStart } from './process_identity.js';
7
+ import { controlIdentitySchema } from './control_schema.js';
8
+ import { parseControlResponse } from './control_schema.js';
9
+ import { createConnection } from 'node:net';
10
+ import { open, readdir, lstat, realpath } from 'node:fs/promises';
11
+ import { constants } from 'node:fs';
12
+ import { homedir } from 'node:os';
13
+ import { join, resolve, dirname } from 'node:path';
14
+ import { StringDecoder } from 'node:string_decoder';
15
+ import { z } from 'zod';
16
+ import { desktopControlToken } from './control_credentials.js';
17
+ async function sendControlRequest(socket, ownerId, publicKey, request, timeoutMs = 15000) {
18
+ let key;
19
+ try {
20
+ key = createPublicKey({ key: Buffer.from(publicKey, 'base64'), format: 'der', type: 'spki' });
21
+ }
22
+ catch {
23
+ throw new DailyError('invalid');
24
+ }
25
+ if (key.asymmetricKeyType !== 'ed25519')
26
+ throw new DailyError('invalid');
27
+ return new Promise(resolve => {
28
+ const client = createConnection(socket);
29
+ const decoder = new StringDecoder('utf8');
30
+ const challenge = randomBytes(32).toString('hex');
31
+ let buffer = '';
32
+ let finished = false;
33
+ let authenticated = false;
34
+ const invalid = (errorClass = authenticated ? 'unknown_schema' : 'invalid') => {
35
+ if (!finished) {
36
+ finished = true;
37
+ client.destroy();
38
+ resolve({ ok: false, error: { class: errorClass } });
39
+ }
40
+ };
41
+ client.setTimeout(timeoutMs, () => invalid());
42
+ client.on('error', () => invalid());
43
+ client.on('end', () => invalid());
44
+ client.on('connect', () => client.write(JSON.stringify({ op: 'hello', challenge }) + '\n'));
45
+ client.on('data', bytes => {
46
+ buffer += decoder.write(bytes);
47
+ if (Buffer.byteLength(buffer) > 1024 * 1024) {
48
+ invalid();
49
+ return;
50
+ }
51
+ while (!finished && buffer.includes('\n')) {
52
+ const newline = buffer.indexOf('\n');
53
+ const line = buffer.slice(0, newline);
54
+ buffer = buffer.slice(newline + 1);
55
+ try {
56
+ const value = JSON.parse(line);
57
+ if (!authenticated) {
58
+ const hello = helloResponseSchema.safeParse(value);
59
+ if (!hello.success || !verifySignature(null, helloMessage(challenge, socket, ownerId), key, Buffer.from(hello.data.signature, 'base64'))) {
60
+ invalid('invalid');
61
+ return;
62
+ }
63
+ authenticated = true;
64
+ client.write(JSON.stringify(request) + '\n');
65
+ continue;
66
+ }
67
+ const op = request && typeof request === 'object' && 'op' in request ? request.op : undefined;
68
+ const parsed = parseControlResponse(op, value);
69
+ finished = true;
70
+ client.destroy();
71
+ resolve(parsed);
72
+ }
73
+ catch {
74
+ invalid();
75
+ }
76
+ }
77
+ });
78
+ });
79
+ }
80
+ export async function runDesktopCommand(args, options = {}) {
81
+ const output = options.output ?? (text => process.stdout.write(text));
82
+ const env = options.env ?? process.env;
83
+ const token = desktopControlToken(env);
84
+ const op = args[0];
85
+ const parsed = {};
86
+ let paneId;
87
+ const usage = () => { output(JSON.stringify({ ok: false, error: { class: 'invalid' } }) + '\n'); return 2; };
88
+ if (!['open', 'list', 'summary', 'stop', 'resume', 'close'].includes(op))
89
+ return usage();
90
+ let start = 1;
91
+ if (!['open', 'list'].includes(op)) {
92
+ if (!/^\d+$/.test(args[1] ?? '') || !Number.isSafeInteger(Number(args[1])))
93
+ return usage();
94
+ paneId = Number(args[1]);
95
+ start = 2;
96
+ }
97
+ for (let i = start; i < args.length; i += 2) {
98
+ const flag = args[i];
99
+ const value = args[i + 1];
100
+ if (!['--tool', '--mode', '--worktree', '--task-file', '--schema'].includes(flag) || value === undefined || value.startsWith('--') || Object.hasOwn(parsed, flag))
101
+ return usage();
102
+ parsed[flag] = value;
103
+ }
104
+ let requestArgs = {};
105
+ if (op === 'open') {
106
+ if (Object.keys(parsed).length !== 5 || !['codex', 'ztc'].includes(parsed['--tool']) || parsed['--mode'] !== 'delegated'
107
+ || !parsed['--worktree'] || !parsed['--task-file'] || !parsed['--schema'])
108
+ return usage();
109
+ requestArgs = { tool: parsed['--tool'], mode: parsed['--mode'], worktree: parsed['--worktree'] === 'new' ? 'new' : resolve(parsed['--worktree']),
110
+ taskFile: resolve(parsed['--task-file']), schemaId: parsed['--schema'] };
111
+ }
112
+ else if (op === 'resume') {
113
+ if (Object.keys(parsed).some(flag => flag !== '--task-file'))
114
+ return usage();
115
+ if (parsed['--task-file'])
116
+ requestArgs.taskFile = resolve(parsed['--task-file']);
117
+ }
118
+ else if (Object.keys(parsed).length)
119
+ return usage();
120
+ if (!env.ZTC_DESKTOP_SOCKET || !token) {
121
+ output(JSON.stringify({ ok: false, error: { class: 'unauthorized' } }) + '\n');
122
+ return 1;
123
+ }
124
+ if (!env.ZTC_DESKTOP_PUBLIC_KEY) {
125
+ output(JSON.stringify({ ok: false, error: { class: 'invalid' } }) + '\n');
126
+ return 1;
127
+ }
128
+ try {
129
+ const directory = join(env.ZTC_CONFIG_DIR ?? join(env.HOME ?? homedir(), '.ztc'), 'desktop');
130
+ const schema = z.strictObject({ socket: z.string(), ownerId: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/), pid: z.number().int().positive(), startedAt: z.number().nonnegative(), uid: z.number().int().nonnegative(), publicKey: z.string().max(256).regex(/^[A-Za-z0-9+/]+={0,2}$/), identities: z.record(z.string().regex(/^[a-f0-9]{64}$/), controlIdentitySchema) });
131
+ const matches = [];
132
+ for (const name of await readdir(directory)) {
133
+ if (!/^control-[a-zA-Z0-9_-]+\.json$/.test(name))
134
+ continue;
135
+ try {
136
+ const handle = await open(join(directory, name), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
137
+ try {
138
+ const stat = await handle.stat();
139
+ if (!stat.isFile() || stat.nlink !== 1 || stat.uid !== process.getuid?.() || (stat.mode & 0o777) !== 0o600 || stat.size > 65536)
140
+ continue;
141
+ const parsed = schema.safeParse(JSON.parse(await handle.readFile('utf8')));
142
+ if (parsed.success && name === `control-${parsed.data.ownerId}.json` && parsed.data.socket === env.ZTC_DESKTOP_SOCKET)
143
+ matches.push(parsed.data);
144
+ }
145
+ finally {
146
+ await handle.close();
147
+ }
148
+ }
149
+ catch { }
150
+ }
151
+ if (matches.length !== 1)
152
+ throw new DailyError('invalid');
153
+ const discovery = matches[0];
154
+ if (discovery.publicKey !== env.ZTC_DESKTOP_PUBLIC_KEY)
155
+ throw new DailyError('invalid');
156
+ const verify = async () => {
157
+ const uid = process.getuid?.();
158
+ const ownerUid = await promisify(execFile)('/bin/ps', ['-p', String(discovery.pid), '-o', 'uid=']).then(value => Number(value.stdout.trim()));
159
+ if (uid === undefined || ownerUid !== uid || discovery.uid !== uid || await observeProcessStart(discovery.pid) !== discovery.startedAt)
160
+ throw new Error('Desktop owner unavailable');
161
+ for (const folder of [directory, dirname(discovery.socket)]) {
162
+ const info = await lstat(folder);
163
+ if (!info.isDirectory() || info.isSymbolicLink() || info.uid !== uid || (info.mode & 0o7777) !== 0o700)
164
+ throw new Error('Invalid desktop directory');
165
+ }
166
+ const socket = await lstat(discovery.socket);
167
+ if (!socket.isSocket() || socket.uid !== uid || (socket.mode & 0o7777) !== 0o600)
168
+ throw new Error('Invalid desktop socket');
169
+ const canonical = await realpath(dirname(discovery.socket));
170
+ if (dirname(discovery.socket) !== directory && canonical !== dirname(discovery.socket))
171
+ throw new Error('Invalid desktop directory');
172
+ };
173
+ await verify();
174
+ const initial = discovery.identities[createHash('sha256').update(token).digest('hex')];
175
+ if (!initial) {
176
+ output(JSON.stringify({ ok: false, error: { class: 'unauthorized' } }) + '\n');
177
+ return 1;
178
+ }
179
+ const send = async (operation, identity, args) => {
180
+ await verify();
181
+ const response = await sendControlRequest(discovery.socket, discovery.ownerId, env.ZTC_DESKTOP_PUBLIC_KEY, { token, op: operation, ...identity, args });
182
+ if (!response.ok)
183
+ return response;
184
+ const result = response.result;
185
+ if ('paneId' in result)
186
+ return result.paneId === identity.paneId ? response : { ok: false, error: { class: 'unknown_schema' } };
187
+ if (result.identity.ownerId !== identity.ownerId || operation !== 'open' && (result.identity.paneId !== identity.paneId || result.identity.sessionId !== identity.sessionId || result.identity.revision < identity.revision))
188
+ return { ok: false, error: { class: 'unknown_schema' } };
189
+ return response;
190
+ };
191
+ let response = await send('list', initial, {});
192
+ if (response.ok && op !== 'list') {
193
+ const list = response.result;
194
+ if (op === 'open')
195
+ response = await send(op, list.identity, requestArgs);
196
+ else {
197
+ const child = list.children.find(child => child.identity.paneId === paneId);
198
+ if (!child)
199
+ response = { ok: false, error: { class: 'unauthorized' } };
200
+ else {
201
+ response = await send('summary', child.identity, {});
202
+ if (response.ok && op !== 'summary')
203
+ response = await send(op, response.result.identity, requestArgs);
204
+ }
205
+ }
206
+ }
207
+ output(JSON.stringify(response) + '\n');
208
+ return response.ok ? 0 : 1;
209
+ }
210
+ catch (error) {
211
+ output(JSON.stringify({ ok: false, error: { class: error instanceof DailyError ? error.class : 'not_found' } }) + '\n');
212
+ return 1;
213
+ }
214
+ }
@@ -0,0 +1,15 @@
1
+ import { z } from 'zod';
2
+ export declare const DESKTOP_CREDENTIAL_FILE_FLAG = "--desktop-credential-file";
3
+ declare const sourceSchema: z.ZodObject<{
4
+ token: z.ZodString;
5
+ socket: z.ZodString;
6
+ publicKey: z.ZodString;
7
+ configRoot: z.ZodString;
8
+ handoff: z.ZodString;
9
+ }, z.core.$strict>;
10
+ export declare function consumeDesktopCredentialHandoff(argv?: string[]): boolean;
11
+ export declare function desktopControlToken(env?: NodeJS.ProcessEnv): string | undefined;
12
+ export declare function readDesktopCredentialSource(path: string): z.infer<typeof sourceSchema>;
13
+ export declare function removeDesktopCredentialSource(pidfile: string): void;
14
+ export declare function desktopCredentialShimEntry(): string[];
15
+ export {};
@@ -0,0 +1,85 @@
1
+ import { constants, closeSync, fstatSync, lstatSync, openSync, readFileSync, realpathSync, rmSync } from 'node:fs';
2
+ import { dirname, basename } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { spawnSync } from 'node:child_process';
5
+ import { z } from 'zod';
6
+ import { checkoutEntry } from './profile_bootstrap.js';
7
+ import { takePaneCredentialHandoff, writePaneCredentialHandoff, removePaneCredentialHandoff } from '../../web/pane_credentials.js';
8
+ export const DESKTOP_CREDENTIAL_FILE_FLAG = '--desktop-credential-file';
9
+ let heldToken = null;
10
+ const sourceName = /^\d+-[a-f0-9-]{36}\.pid\.credential$/;
11
+ const sourceSchema = z.strictObject({ token: z.string().regex(/^[a-f0-9]{64}$/), socket: z.string().min(1), publicKey: z.string().min(1), configRoot: z.string().min(1), handoff: z.string().min(1) });
12
+ export function consumeDesktopCredentialHandoff(argv = process.argv) {
13
+ const end = argv.indexOf('--');
14
+ const at = argv.indexOf(DESKTOP_CREDENTIAL_FILE_FLAG);
15
+ if (at < 0 || end >= 0 && at > end)
16
+ return false;
17
+ const value = argv[at + 1];
18
+ const path = value !== undefined && !value.startsWith('-') ? value : '';
19
+ argv.splice(at, path ? 2 : 1);
20
+ const token = takePaneCredentialHandoff(path);
21
+ if (token === null || !/^[a-f0-9]{64}$/.test(token))
22
+ return false;
23
+ heldToken = token;
24
+ return true;
25
+ }
26
+ export function desktopControlToken(env = process.env) {
27
+ return env === process.env ? heldToken ?? env.ZTC_DESKTOP_TOKEN : env.ZTC_DESKTOP_TOKEN;
28
+ }
29
+ export function readDesktopCredentialSource(path) {
30
+ if (!sourceName.test(basename(path)))
31
+ throw new Error('Invalid desktop credential source');
32
+ const directory = dirname(path);
33
+ const info = lstatSync(directory);
34
+ if (!info.isDirectory() || info.isSymbolicLink() || info.uid !== process.getuid?.() || (info.mode & 0o7777) !== 0o700 || realpathSync(directory) !== directory)
35
+ throw new Error('Invalid desktop credential directory');
36
+ const file = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
37
+ try {
38
+ const info = fstatSync(file);
39
+ if (!info.isFile() || info.uid !== process.getuid?.() || info.nlink !== 1 || (info.mode & 0o7777) !== 0o600 || info.size > 4096)
40
+ throw new Error('Invalid desktop credential source');
41
+ return sourceSchema.parse(JSON.parse(readFileSync(file, 'utf8')));
42
+ }
43
+ finally {
44
+ closeSync(file);
45
+ }
46
+ }
47
+ export function removeDesktopCredentialSource(pidfile) {
48
+ const path = pidfile + '.credential';
49
+ let source;
50
+ try {
51
+ source = readDesktopCredentialSource(path);
52
+ }
53
+ catch {
54
+ return;
55
+ }
56
+ removePaneCredentialHandoff(source.handoff);
57
+ rmSync(path, { force: true });
58
+ rmSync(pidfile + '.bin', { recursive: true, force: true });
59
+ }
60
+ function runShim() {
61
+ let handoff;
62
+ try {
63
+ const source = readDesktopCredentialSource(process.argv[2]);
64
+ handoff = writePaneCredentialHandoff(source.token);
65
+ const env = { ...process.env, ZTC_CONFIG_DIR: source.configRoot, ZTC_DESKTOP_SOCKET: source.socket, ZTC_DESKTOP_PUBLIC_KEY: source.publicKey };
66
+ delete env.ZTC_DESKTOP_TOKEN;
67
+ const entry = checkoutEntry();
68
+ const result = spawnSync(entry.command, [...entry.args, DESKTOP_CREDENTIAL_FILE_FLAG, handoff, ...process.argv.slice(3)], { env, stdio: 'inherit' });
69
+ process.exitCode = result.status ?? 1;
70
+ }
71
+ catch {
72
+ process.stderr.write('Desktop credential unavailable\n');
73
+ process.exitCode = 1;
74
+ }
75
+ finally {
76
+ if (handoff)
77
+ removePaneCredentialHandoff(handoff);
78
+ }
79
+ }
80
+ if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1])
81
+ runShim();
82
+ export function desktopCredentialShimEntry() {
83
+ const typescript = import.meta.url.endsWith('.ts');
84
+ return [process.execPath, ...(typescript ? ['--import', fileURLToPath(new URL('../../../scripts/test-ts-loader.mjs', import.meta.url))] : []), fileURLToPath(import.meta.url)];
85
+ }
@@ -0,0 +1,10 @@
1
+ import { z } from 'zod';
2
+ export declare const helloRequestSchema: z.ZodObject<{
3
+ op: z.ZodLiteral<"hello">;
4
+ challenge: z.ZodString;
5
+ }, z.core.$strict>;
6
+ export declare const helloResponseSchema: z.ZodObject<{
7
+ op: z.ZodLiteral<"hello">;
8
+ signature: z.ZodString;
9
+ }, z.core.$strict>;
10
+ export declare function helloMessage(challenge: string, socket: string, ownerId: string): Buffer;
@@ -0,0 +1,6 @@
1
+ import { z } from 'zod';
2
+ export const helloRequestSchema = z.strictObject({ op: z.literal('hello'), challenge: z.string().regex(/^[a-f0-9]{64}$/) });
3
+ export const helloResponseSchema = z.strictObject({ op: z.literal('hello'), signature: z.string().regex(/^[A-Za-z0-9+/]{86}==$/) });
4
+ export function helloMessage(challenge, socket, ownerId) {
5
+ return Buffer.concat([Buffer.from(challenge, 'hex'), Buffer.from(socket), Buffer.from(ownerId)]);
6
+ }
@@ -0,0 +1,39 @@
1
+ import type { DelegatedAuthView } from './router_state.js';
2
+ import type { ChildSummary } from './summary.js';
3
+ export type ControlErrorClass = 'unauthorized' | 'stale' | 'forbidden_interactive' | 'unknown_schema' | 'lease_refused' | 'launch_refused' | 'not_found' | 'invalid';
4
+ export declare class DailyError extends Error {
5
+ readonly class: ControlErrorClass;
6
+ constructor(errorClass: ControlErrorClass);
7
+ }
8
+ export interface ControlIdentity {
9
+ paneId: number;
10
+ sessionId: string | null;
11
+ ownerId: string;
12
+ revision: number;
13
+ }
14
+ export type StatusPaneState = 'pending' | 'ready' | 'unavailable';
15
+ export interface ChildSnapshot {
16
+ routerAuth: DelegatedAuthView;
17
+ status_pane: StatusPaneState;
18
+ summary: ChildSummary;
19
+ identity: ControlIdentity;
20
+ orphaned: boolean;
21
+ result: Record<string, string | number> | null;
22
+ }
23
+ export type ControlResult = ChildSnapshot | {
24
+ children: ChildSnapshot[];
25
+ identity: ControlIdentity;
26
+ status_pane: StatusPaneState;
27
+ routerAuth: DelegatedAuthView;
28
+ } | {
29
+ paneId: number;
30
+ };
31
+ export type ControlResponse = {
32
+ ok: true;
33
+ result: ControlResult;
34
+ } | {
35
+ ok: false;
36
+ error: {
37
+ class: ControlErrorClass;
38
+ };
39
+ };
@@ -0,0 +1,4 @@
1
+ export class DailyError extends Error {
2
+ class;
3
+ constructor(errorClass) { super(errorClass); this.class = errorClass; }
4
+ }
@@ -0,0 +1,9 @@
1
+ import { z } from 'zod';
2
+ import type { ControlResponse } from './control_protocol.js';
3
+ export declare const controlIdentitySchema: z.ZodObject<{
4
+ paneId: z.ZodNumber;
5
+ sessionId: z.ZodNullable<z.ZodUUID>;
6
+ ownerId: z.ZodString;
7
+ revision: z.ZodNumber;
8
+ }, z.core.$strict>;
9
+ export declare function parseControlResponse(op: unknown, value: unknown): ControlResponse;