@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,1048 @@
1
+ import { OwnerSeals } from './owner_seals.js';
2
+ import { ownerDirectory, atomicOwnerFile } from './owner_files.js';
3
+ import { removeLegacyCodexHomes } from './legacy_codex_homes.js';
4
+ import { execFile } from 'node:child_process';
5
+ import { constants } from 'node:fs';
6
+ import { access, mkdir, realpath, open } from 'node:fs/promises';
7
+ import { homedir } from 'node:os';
8
+ import { basename, join, resolve, delimiter } from 'node:path';
9
+ import { randomUUID } from 'node:crypto';
10
+ import { promisify } from 'node:util';
11
+ import { setTimeout as delay } from 'node:timers/promises';
12
+ import { inspectWorkspaceSessions, prepareWorkspaceIsolation } from '../../workspace_collision.js';
13
+ import { getVersion } from '../../utils/version.js';
14
+ import { newZtcPaneRouteArgs } from '../../panes/ztc_launch.js';
15
+ import { DailyStore } from './daily_store.js';
16
+ import { createControlServer, readTaskFile } from './control_server.js';
17
+ import { createApprovalBroker } from './broker.js';
18
+ import { acquireLease, applyOverride, bindLeaseSession, bindLeasePane, adoptLeaseOwner, markLeaseUnverified, releaseUnstartedLease, releaseUnstartedReadLease, heartbeat, readLease, releaseOnExit } from './lease.js';
19
+ import { readWorktreeIdentity, policyHash } from './native_tool.js';
20
+ import { recipeFor, rebuildNativeLaunch } from './recipes.js';
21
+ import { schemaRegistry } from './schema_registry.js';
22
+ import { checkoutEntry, delegatedSkillRoots, delegatedAuthState, refreshDelegatedProfile, logoutDelegatedProfile } from './profile_bootstrap.js';
23
+ import { buildDelegatedZtcLaunch, ensureDelegatedProfile, resolveDelegatedPolicy, DelegatedLaunchError } from './delegated_ztc_contract.js';
24
+ import { deriveRouterAuthState, deriveRouterFundingState } from './router_state.js';
25
+ import { runCodexExec } from './codex_exec_adapter.js';
26
+ import { runZtcHeadless } from './ztc_headless_adapter.js';
27
+ import { prepareNativeLauncher, observeLauncher, terminateLauncherGroup, stopNativePane, cleanupNativeLauncherCredentials } from './native_pane_launcher.js';
28
+ import { observeProcessStart, groupMembersOf, validateIdentity } from './process_identity.js';
29
+ import { savedNativeRecord, parseNativeRecords, savedBrokerUrl } from './native_records.js';
30
+ import { generateToken } from './enrollment.js';
31
+ import { DailyError } from './control_protocol.js';
32
+ const exec = promisify(execFile);
33
+ class NativeRendererRefusal extends Error {
34
+ }
35
+ export const nativeChoices = Object.freeze([
36
+ { value: 'native:codex:delegated', label: 'Codex (delegated)' },
37
+ { value: 'native:ztc:interactive', label: 'ZTC (interactive)' },
38
+ { value: 'native:ztc:delegated', label: 'ZTC (delegated)' },
39
+ { value: 'native:shell:interactive', label: 'Shell (native, leased)' },
40
+ ]);
41
+ export function canResumeNative(record, lease) {
42
+ return record.identity.state === 'bound' && record.identity.canonicalId !== null && record.launch.cwd.length > 0
43
+ && (record.launch.tool !== 'codex' || record.launch.mode !== 'delegated' || record.launch.policy?.capabilities.shell_exec === true)
44
+ && record.launch.cliVersion !== null && !('unsupported' in recipeFor(record.launch.tool, record.launch.mode, record.launch.cliVersion))
45
+ && record.outcome.stopState !== 'running' && lease?.lease.ownerState === 'exited' && record.launch.sandbox !== null && record.launch.approvalPolicy !== null && !!lease && !lease.lease.usedWritable
46
+ && record.leaseId === lease.lease.identityHash && record.identity.canonicalId === lease.lease.ownerSessionId && record.paneId === lease.lease.ownerPaneId;
47
+ }
48
+ export async function validateNativeResume(record, lease, resolvePolicy) {
49
+ if (lease?.lease.usedWritable)
50
+ throw new Error('Writable session, quarantined; isolate before starting new work');
51
+ if (!canResumeNative(record, lease))
52
+ throw new Error('Cannot resume this exact session');
53
+ const current = await readWorktreeIdentity(record.launch.cwd);
54
+ if (current.repositoryRoot !== record.launch.worktree.repositoryRoot || current.gitCommonDir !== record.launch.worktree.gitCommonDir
55
+ || current.branch !== record.launch.worktree.branch || current.head !== record.launch.worktree.head)
56
+ throw new Error('Saved worktree identity changed');
57
+ if (record.launch.tool === 'ztc' && record.launch.mode === 'delegated') {
58
+ if (!resolvePolicy || !record.launch.policy)
59
+ throw new Error('Saved policy is unavailable');
60
+ const policy = await resolvePolicy();
61
+ policy.brokerUrl = record.launch.policy.brokerUrl;
62
+ policy.outputSink = record.launch.policy.outputSink;
63
+ policy.schemaId = record.launch.policy.schemaId;
64
+ policy.schemaHash = record.launch.policy.schemaHash;
65
+ if (policyHash(policy) !== record.launch.policy.policyHash)
66
+ throw new Error('Resume policy changed');
67
+ }
68
+ }
69
+ export async function answerDesktopApproval(broker, select) {
70
+ const approval = broker.pending[0];
71
+ if (!approval)
72
+ return;
73
+ const answer = await select(`Pane ${approval.childPaneId}: ${approval.capabilities.join(', ') || 'unknown'}`, [{ value: 'denied', label: 'Deny' }, ...(approval.approvable ? [{ value: 'approved', label: 'Approve' }] : [])]);
74
+ if (broker.pending.some(item => item.requestId === approval.requestId))
75
+ broker.decide(approval.requestId, answer === 'approved' && approval.approvable ? 'approved' : 'denied', 'desktop_human');
76
+ }
77
+ export function safeDailyMessage(error) {
78
+ if (error instanceof DailyError)
79
+ return `Native operation refused: ${error.class}`;
80
+ if (error instanceof DelegatedLaunchError)
81
+ return `Delegated launch refused: ${error.code}`;
82
+ const messages = new Set(['Writable session, quarantined; isolate before starting new work', 'Cannot resume this exact session',
83
+ 'Saved worktree identity changed', 'Saved policy is unavailable', 'Resume policy changed', 'Native CLI version unsupported',
84
+ 'Native CLI unavailable', 'Native CLI identity changed', 'Native launch cancelled', 'Risk override cancelled', 'Desktop closed',
85
+ 'Native pane still active', 'Native pane changed; choose it again', 'Previous desktop owner is still active or unverified',
86
+ 'Live lease identity cannot be adopted', 'Live process identity cannot be adopted', 'Native action pending or desktop closed',
87
+ 'Desktop closed or restoring', 'Stop native panes before restoring a workspace',
88
+ 'Cannot resume this exact session; start a fresh pane or isolate a quarantined worktree']);
89
+ return error instanceof Error && messages.has(error.message) ? error.message : 'Native operation refused';
90
+ }
91
+ export class DesktopDaily {
92
+ ownerId;
93
+ host;
94
+ store;
95
+ control;
96
+ broker;
97
+ actions = new Set();
98
+ pendingIds = new Set();
99
+ cancelledOpenings = new Set();
100
+ seals;
101
+ ownerStartMs = 0;
102
+ rootToken = '';
103
+ persistQueues = new Map();
104
+ leaseQueues = new WeakMap();
105
+ authAbort = new AbortController();
106
+ live = new Map();
107
+ directory;
108
+ configRoot;
109
+ timer = null;
110
+ refreshing = false;
111
+ polling = false;
112
+ closed = false;
113
+ dialog = false;
114
+ openings = 0;
115
+ restoring = false;
116
+ childWindow = null;
117
+ serial = Promise.resolve();
118
+ lastAuth = 0;
119
+ auth = deriveRouterAuthState(undefined, null, Date.now());
120
+ funding = deriveRouterFundingState(undefined);
121
+ constructor(ownerId, host) {
122
+ this.ownerId = ownerId;
123
+ this.host = host;
124
+ this.store = new DailyStore(ownerId);
125
+ this.configRoot = host.configRoot ?? process.env.ZTC_CONFIG_DIR ?? join(homedir(), '.ztc');
126
+ this.directory = join(this.configRoot, 'desktop', `owner-${ownerId}`);
127
+ }
128
+ async start() {
129
+ await ownerDirectory(this.directory, this.configRoot);
130
+ await removeLegacyCodexHomes(this.configRoot);
131
+ this.seals = await OwnerSeals.open(join(this.configRoot, 'desktop'));
132
+ const startedAt = await observeProcessStart(process.pid);
133
+ if (startedAt === null)
134
+ throw new DailyError('launch_refused');
135
+ this.ownerStartMs = startedAt;
136
+ try {
137
+ this.broker = await createApprovalBroker();
138
+ const root = await this.record(0, 'ztc', 'interactive', this.host.cwd());
139
+ root.identity = { canonicalId: null, state: 'unbound', source: 'none', validatedAt: null };
140
+ this.rootToken = (await this.store.registerParent(root)).token;
141
+ this.control = await createControlServer({ configRoot: this.configRoot, store: this.store, managed: true,
142
+ open: request => this.openDelegated(request), stop: record => this.stop(record.paneId, false),
143
+ resume: async (record, prompt) => { await this.resume(record.paneId, prompt); return this.store.getRecord(record.paneId); },
144
+ close: paneId => this.closePane(paneId) });
145
+ this.timer = setInterval(() => { void this.poll(); }, 500);
146
+ this.timer.unref();
147
+ void this.refreshRouter();
148
+ }
149
+ catch (error) {
150
+ await this.control?.close().catch(() => { });
151
+ await this.broker?.close().catch(() => { });
152
+ throw error;
153
+ }
154
+ }
155
+ snapshot() {
156
+ const auth = ['authenticated', 'unavailable', 'stale'].includes(this.auth.state) && this.auth.checkedAt !== null && Date.now() - this.auth.checkedAt > 600000
157
+ ? deriveRouterAuthState(new Error('stale'), this.auth, Date.now()) : this.auth;
158
+ return { status_pane: this.store.statusPane, children: this.store.childrenForOwner().map(item => item.summary), routerAuth: { ...auth, ageMs: auth.checkedAt === null ? null : Math.max(0, Date.now() - auth.checkedAt) }, routerFunding: this.funding };
159
+ }
160
+ hasPane(paneId) { return paneId !== 0 && (this.pendingIds.has(paneId) || this.store.hasRecord(paneId)); }
161
+ get publicKey() { return this.control.publicKey; }
162
+ exportRecords() {
163
+ const records = this.store.exportRecords();
164
+ delete records['0'];
165
+ return records;
166
+ }
167
+ beforeRestore() {
168
+ if (this.restoring)
169
+ throw new Error('A workspace restore is in progress; try again when it finishes.');
170
+ if (this.openings || this.actions.size || [...this.live.values()].some(item => item.completion !== undefined || item.closing !== undefined || item.started && item.record.outcome.stopState !== 'leader_exited'))
171
+ throw new Error('Stop native panes before restoring a workspace');
172
+ }
173
+ afterRestore() { this.restoring = false; }
174
+ async prepareRestoreRecords(input) {
175
+ this.beforeRestore();
176
+ const records = parseNativeRecords(input);
177
+ const url = savedBrokerUrl(records);
178
+ this.restoring = true;
179
+ let replacement = null;
180
+ try {
181
+ if (url && url.href !== this.broker.url) {
182
+ try {
183
+ replacement = await createApprovalBroker({ port: Number(url.port) });
184
+ }
185
+ catch (error) {
186
+ if (error.code !== 'EADDRINUSE')
187
+ throw error;
188
+ }
189
+ }
190
+ }
191
+ catch (error) {
192
+ this.restoring = false;
193
+ throw error;
194
+ }
195
+ let restored = false;
196
+ let closed = false;
197
+ return {
198
+ restore: async () => {
199
+ if (restored || closed)
200
+ throw new Error('Native restore plan is no longer available');
201
+ restored = true;
202
+ if (replacement) {
203
+ const previous = this.broker;
204
+ this.broker = replacement;
205
+ replacement = null;
206
+ await previous.close().catch(() => this.host.notify('Previous approval broker cleanup unavailable'));
207
+ }
208
+ await this.importRestoredRecords(records);
209
+ },
210
+ close: async () => {
211
+ if (closed)
212
+ return;
213
+ closed = true;
214
+ try {
215
+ await replacement?.close();
216
+ }
217
+ finally {
218
+ this.afterRestore();
219
+ }
220
+ },
221
+ };
222
+ }
223
+ async restoreRecords(input) {
224
+ const plan = await this.prepareRestoreRecords(input);
225
+ try {
226
+ await plan.restore();
227
+ }
228
+ finally {
229
+ await plan.close();
230
+ }
231
+ }
232
+ async importRestoredRecords(records) {
233
+ this.live.clear();
234
+ this.pendingIds.clear();
235
+ this.childWindow = null;
236
+ this.store.clearChildren();
237
+ await this.store.importRecords(records, true);
238
+ for (const record of Object.values(records)) {
239
+ const restored = this.store.getRecord(record.paneId);
240
+ const observedLease = await readLease(restored.launch.worktree, this.leaseOptions()).catch(() => null);
241
+ let lease = restored.launch.tool === 'ztc' && restored.launch.mode === 'delegated' && restored.launch.policy?.brokerUrl !== this.broker.url ? null : observedLease;
242
+ if (lease) {
243
+ try {
244
+ if (!/^[a-zA-Z0-9_-]{1,64}$/.test(lease.lease.desktopOwnerId) || restored.leaseId !== lease.lease.identityHash
245
+ || restored.identity.canonicalId !== lease.lease.ownerSessionId || restored.paneId !== lease.lease.ownerPaneId)
246
+ throw new Error('Unverified lease history');
247
+ const directory = join(this.configRoot, 'desktop', `owner-${lease.lease.desktopOwnerId}`);
248
+ await ownerDirectory(directory, this.configRoot);
249
+ const handle = await open(join(directory, `record-${restored.paneId}.json`), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
250
+ try {
251
+ const info = await handle.stat();
252
+ if (!info.isFile() || info.nlink !== 1 || info.uid !== process.getuid?.() || (info.mode & 0o777) !== 0o600 || info.size > 65536)
253
+ throw new Error('Unverified lease history');
254
+ const saved = parseNativeRecords({ [restored.paneId]: JSON.parse(await handle.readFile('utf8')) }, undefined, true)[restored.paneId];
255
+ if (saved.controlOwnerPid === undefined || saved.controlOwnerStartMs === undefined || !this.seals.verify(saved) || saved.leaseAcquiredAt !== lease.lease.acquiredAt || saved.launchOwnerId !== lease.lease.desktopOwnerId)
256
+ throw new Error('Unverified launch provenance');
257
+ if (saved.leaseId !== restored.leaseId || saved.identity.canonicalId !== restored.identity.canonicalId
258
+ || saved.launch.tool !== restored.launch.tool || saved.launch.cwd !== restored.launch.cwd)
259
+ throw new Error('Unverified lease history');
260
+ restored.launch = saved.launch;
261
+ restored.provenance = saved.provenance;
262
+ restored.launchOwnerId = saved.launchOwnerId;
263
+ restored.leaseAcquiredAt = saved.leaseAcquiredAt;
264
+ restored.controlOwnerPid = saved.controlOwnerPid;
265
+ restored.controlOwnerStartMs = saved.controlOwnerStartMs;
266
+ this.store.updateRecord(restored);
267
+ }
268
+ finally {
269
+ await handle.close();
270
+ }
271
+ }
272
+ catch {
273
+ lease = null;
274
+ }
275
+ }
276
+ if (lease) {
277
+ this.live.set(record.paneId, { record: restored, lease: lease.lease, pidfile: null, started: false, lastHeartbeat: 0 });
278
+ this.store.setLease(record.paneId, lease);
279
+ }
280
+ const display = lease ?? (observedLease ? { ...observedLease, state: 'quarantined', label: null } : null);
281
+ if (!lease && display)
282
+ this.store.observeLease(record.paneId, display);
283
+ this.label(restored, display);
284
+ this.host.track(restored);
285
+ }
286
+ this.host.changed();
287
+ }
288
+ async refreshRouter() {
289
+ if (this.refreshing || this.closed)
290
+ return;
291
+ this.refreshing = true;
292
+ this.lastAuth = Date.now();
293
+ const entry = checkoutEntry();
294
+ const command = async (op) => {
295
+ const result = await exec(entry.command, [...entry.args, '--profile', 'desktop-delegated', 'auth', op, '--json'], { env: { ...(this.host.env ?? process.env), ZTC_CONFIG_DIR: this.configRoot }, timeout: 15000, maxBuffer: 65536, signal: this.authAbort.signal });
296
+ return JSON.parse(result.stdout);
297
+ };
298
+ const [status, readiness] = await Promise.allSettled([delegatedAuthState(this.configRoot, this.auth, Date.now(), this.host.env), command('readiness')]);
299
+ this.auth = status.status === 'fulfilled' ? status.value : deriveRouterAuthState(status.reason, this.auth, Date.now());
300
+ this.store.setRouterAuth(this.auth);
301
+ this.funding = deriveRouterFundingState(readiness.status === 'fulfilled' ? readiness.value : readiness.reason);
302
+ this.refreshing = false;
303
+ this.host.changed();
304
+ }
305
+ /** Opens the native pane or worker the New pane chooser was given; an interactive pane splits `target` when named. */
306
+ async pick(value, cwd = this.host.cwd(), target) {
307
+ if (value === 'native:router-refresh') {
308
+ await refreshDelegatedProfile(this.configRoot);
309
+ await this.refreshRouter();
310
+ return;
311
+ }
312
+ if (value === 'native:router-signout') {
313
+ await logoutDelegatedProfile(this.configRoot);
314
+ await this.refreshRouter();
315
+ return;
316
+ }
317
+ if (!/^native:(shell|claude_code|codex):interactive$/.test(value) && !nativeChoices.some(choice => choice.value === value))
318
+ throw new Error('Unknown native pane choice');
319
+ const [, tool, mode] = value.split(':');
320
+ const where = await this.host.select('Worktree', [{ value: 'new', label: 'New isolated worktree (default)' }, { value: 'current', label: 'Current worktree' }]);
321
+ if (where === null)
322
+ return;
323
+ const worktree = where === 'new' ? await this.isolate(cwd) : cwd;
324
+ if (mode === 'delegated') {
325
+ const path = await this.host.input('Task file (absolute path)');
326
+ if (!path)
327
+ return;
328
+ const task = await readTaskFile(resolve(path));
329
+ const opened = await this.openDelegated({ tool: tool, mode, worktree, task, schemaId: 'fixture-count-v1' }, true);
330
+ try {
331
+ await this.store.addChild(this.rootToken, opened.record, opened);
332
+ opened.start?.();
333
+ }
334
+ catch (error) {
335
+ await opened.cancel?.();
336
+ throw error;
337
+ }
338
+ }
339
+ else
340
+ await this.interactive(tool, worktree, undefined, target);
341
+ }
342
+ leaseOptions() { return { directory: join(this.configRoot, 'desktop-leases') }; }
343
+ async isolate(cwd) {
344
+ const parent = join(this.host.env?.HOME ?? homedir(), 'Projects', 'Work', 'zerg-lanes');
345
+ await mkdir(parent, { recursive: true });
346
+ const snapshot = await inspectWorkspaceSessions(cwd, `desktop-${this.ownerId}`);
347
+ return (await prepareWorkspaceIsolation(snapshot, join(parent, `daily-${randomUUID()}`))).cwd;
348
+ }
349
+ async request(command, match, dispatched) {
350
+ return new Promise((resolve, reject) => {
351
+ let off = () => { };
352
+ const timer = setTimeout(() => { off(); reject(new Error('Native pane renderer unavailable')); }, 10000);
353
+ off = this.host.transport.on(event => {
354
+ const refusal = event.type === 'error' && 'request_id' in command && command.request_id !== undefined
355
+ && (event.request_id === command.request_id || command.type === 'create_pane' && event.request_id === undefined
356
+ && event.message.startsWith('create_pane failed') && this.host.transport.isOnlyPendingPaneCreate?.(command.request_id) === true);
357
+ if (match(event) || refusal) {
358
+ clearTimeout(timer);
359
+ off();
360
+ if (event.type === 'pane_created')
361
+ this.pendingIds.add(event.pane_id);
362
+ if (event.type !== 'error')
363
+ resolve(event);
364
+ else if (event.message === 'Native pane renderer timed out')
365
+ reject(new Error('Native pane renderer unavailable'));
366
+ else
367
+ reject(new NativeRendererRefusal('Native pane renderer refused launch'));
368
+ }
369
+ });
370
+ dispatched?.();
371
+ if (!this.host.transport.send(command)) {
372
+ clearTimeout(timer);
373
+ off();
374
+ reject(new NativeRendererRefusal('Native pane renderer unavailable'));
375
+ }
376
+ });
377
+ }
378
+ async placeholder() {
379
+ let release;
380
+ const before = this.serial;
381
+ this.serial = new Promise(resolve => { release = resolve; });
382
+ await before;
383
+ try {
384
+ if (this.childWindow === null) {
385
+ const snapshot = await this.request({ type: 'get_session_state' }, event => event.type === 'session_state');
386
+ if (snapshot.type !== 'session_state')
387
+ throw new Error('Native workspace unavailable');
388
+ this.childWindow = Math.max(0, ...(snapshot.state.windows ?? []).map(window => window.id)) + 1;
389
+ }
390
+ const title = `Native ${randomUUID()}`;
391
+ const event = await this.request({ type: 'create_feed_pane', title, lines: ['Inactive native pane'], trim: 500 }, event => event.type === 'pane_created' && event.title === title);
392
+ if (event.type !== 'pane_created')
393
+ throw new Error('Native pane unavailable');
394
+ return event.pane_id;
395
+ }
396
+ finally {
397
+ release();
398
+ }
399
+ }
400
+ async record(paneId, tool, mode, cwd) {
401
+ const worktree = await readWorktreeIdentity(cwd).catch(error => { if (paneId !== 0)
402
+ throw error; return { repositoryRoot: resolve(cwd), gitCommonDir: resolve(cwd), branch: null, head: null }; });
403
+ const entry = checkoutEntry();
404
+ return { recordVersion: 1, paneId, launch: { tool, mode, command: tool === 'ztc' ? entry.command : tool === 'claude_code' ? 'claude' : tool === 'shell' ? this.host.env?.SHELL ?? process.env.SHELL ?? '/bin/bash' : tool,
405
+ args: tool === 'ztc' && mode === 'interactive' ? [...entry.args] : tool === 'shell' ? ['-l'] : [], cwd: await realpath(cwd), worktree,
406
+ profile: null, model: tool === 'ztc' && mode === 'delegated' ? 'modal/deepseek-v4.1-flash' : null, effort: null,
407
+ sandbox: mode === 'delegated' ? 'read-only' : null, approvalPolicy: mode === 'delegated' ? 'never' : null, cliVersion: tool === 'ztc' ? getVersion() : null,
408
+ versionRange: tool === 'claude_code' ? '2.1.x' : tool === 'codex' ? '0.166.x' : tool === 'shell' ? '*' : getVersion() },
409
+ identity: tool === 'codex' || tool === 'shell' ? { canonicalId: null, state: 'unbound', source: 'none', validatedAt: null }
410
+ : { canonicalId: randomUUID(), state: 'bound', source: 'launcher_assigned', validatedAt: Date.now() },
411
+ process: null, outcome: { exit: null, stopState: 'unknown', survivors: [], containment: 'unverified' }, enrollmentId: null, leaseId: null };
412
+ }
413
+ async version(record, resume = false) {
414
+ const savedCommand = record.launch.command;
415
+ rebuildNativeLaunch(record);
416
+ if (record.launch.tool === 'ztc')
417
+ return;
418
+ const before = { command: record.launch.command, version: record.launch.cliVersion };
419
+ let command = null;
420
+ for (const candidate of record.launch.command.startsWith('/') ? [record.launch.command] : (this.host.env?.PATH ?? process.env.PATH ?? '').split(delimiter).map(root => join(root, record.launch.command))) {
421
+ try {
422
+ await access(candidate);
423
+ command = await realpath(candidate);
424
+ break;
425
+ }
426
+ catch { }
427
+ }
428
+ if (!command)
429
+ throw new Error('Native CLI unavailable');
430
+ const { stdout } = await exec(command, ['--version'], { env: this.host.env ?? process.env, timeout: 5000, maxBuffer: 1024 });
431
+ const reported = /(?:codex-cli )?(\d+\.\d+(?:\.\d+)?)/.exec(stdout)?.[1];
432
+ const version = reported && reported.split('.').length === 2 ? `${reported}.0` : reported;
433
+ if (!version || 'unsupported' in recipeFor(record.launch.tool, record.launch.mode, version))
434
+ throw new Error('Native CLI version unsupported');
435
+ if (resume && (savedCommand.startsWith('/') && savedCommand !== command || before.version !== version))
436
+ throw new Error('Native CLI identity changed');
437
+ record.launch.command = command;
438
+ record.launch.cliVersion = version;
439
+ }
440
+ async lease(record, human) {
441
+ for (;;) {
442
+ const owner = { ownerPaneId: record.paneId, ownerSessionId: record.identity.canonicalId, tool: record.launch.tool, leaderPid: null,
443
+ leaderStartMs: null, pgid: null, desktopOwnerId: this.ownerId, usedWritable: record.launch.mode === 'interactive' };
444
+ const admission = await acquireLease(record.launch.worktree, owner, this.leaseOptions());
445
+ if (admission.ok) {
446
+ record.leaseId = admission.lease.identityHash;
447
+ return admission.lease;
448
+ }
449
+ if (!human)
450
+ throw new DailyError('lease_refused');
451
+ const view = await readLease(record.launch.worktree, this.leaseOptions());
452
+ const answer = await this.host.select(`Lease refused: ${admission.reason}; pane ${view?.lease.ownerPaneId ?? 'unknown'} session ${view?.lease.ownerSessionId ?? 'unknown'}`, [{ value: 'isolate', label: 'Isolate into a new worktree' }, { value: 'risk', label: 'Risk override: descendants and exclusivity cannot be verified' }, { value: 'cancel', label: 'Cancel' }]);
453
+ if (answer === 'isolate') {
454
+ record.launch.cwd = await this.isolate(record.launch.cwd);
455
+ record.launch.worktree = await readWorktreeIdentity(record.launch.cwd);
456
+ continue;
457
+ }
458
+ if (answer === 'risk') {
459
+ const why = await this.host.input('Reason for risk override');
460
+ if (!why?.trim())
461
+ throw new Error('Risk override cancelled');
462
+ const lease = await applyOverride(record.launch.worktree, owner, { by: 'desktop_human', who: this.host.env?.USER ?? process.env.USER ?? 'desktop_human', why }, this.leaseOptions());
463
+ record.leaseId = lease.identityHash;
464
+ record.outcome.containment = 'override';
465
+ for (const live of this.live.values())
466
+ if (live.lease.identityHash === lease.identityHash) {
467
+ live.record.outcome.containment = 'override';
468
+ this.publish(live.record);
469
+ this.label(live.record, { lease, state: 'held', label: 'exclusivity unverified' });
470
+ }
471
+ return lease;
472
+ }
473
+ throw new Error('Native launch cancelled');
474
+ }
475
+ }
476
+ label(record, lease) {
477
+ const leaseState = lease?.lease.containment === 'override' ? 'exclusivity unverified' : lease?.state ?? 'none';
478
+ const orphan = record.enrollmentId !== null && this.store.snapshotForOwner(record.paneId).orphaned ? ' orphaned' : '';
479
+ const title = `${record.launch.tool} ${record.launch.mode}${canResumeNative(record, this.store.leaseFor(record.paneId)) ? '' : ' not resumable'} · ${basename(record.launch.cwd)} · ${leaseState} · ${record.identity.state}${orphan} · ${record.outcome.stopState}${record.outcome.exit?.code == null ? '' : ` (${record.outcome.exit.code})`}`;
480
+ this.host.transport.send({ type: 'set_pane_labels', pane_id: record.paneId, labels: { manual_title: title, project: record.launch.cwd, task: record.launch.mode === 'interactive' ? 'human input only' : 'untrusted feed', updated_at_ms: Date.now() } });
481
+ this.host.transport.send({ type: 'set_pane_title', pane_id: record.paneId, title, source: 'manual' });
482
+ }
483
+ async persist(record) {
484
+ const clean = savedNativeRecord(record, true);
485
+ clean.launchOwnerId = this.ownerId;
486
+ clean.leaseAcquiredAt = this.live.get(record.paneId)?.lease.acquiredAt;
487
+ clean.launchSeal = this.seals.sign(clean);
488
+ const queued = (this.persistQueues.get(record.paneId) ?? Promise.resolve()).then(async () => {
489
+ await atomicOwnerFile(join(this.directory, `record-${record.paneId}.json`), JSON.stringify(clean));
490
+ });
491
+ this.persistQueues.set(record.paneId, queued.catch(() => { }));
492
+ await queued;
493
+ }
494
+ publish(record, observation) {
495
+ if (this.closed)
496
+ return;
497
+ const live = this.live.get(record.paneId);
498
+ if (!live)
499
+ return;
500
+ if (live.lease.containment === 'override')
501
+ record.outcome.containment = 'override';
502
+ record.launchOwnerId = this.ownerId;
503
+ record.leaseAcquiredAt = live.lease.acquiredAt;
504
+ record.controlOwnerPid = process.pid;
505
+ record.controlOwnerStartMs = this.ownerStartMs;
506
+ if (observation)
507
+ this.store.setObservation(record, observation);
508
+ else
509
+ this.store.updateRecord(record);
510
+ record = this.store.getRecord(record.paneId);
511
+ live.record = structuredClone(record);
512
+ this.host.track(this.store.getRecord(record.paneId));
513
+ this.label(record, this.store.leaseFor(record.paneId) ?? { lease: live.lease, state: live.lease.usedWritable && record.outcome.stopState !== 'running' ? 'quarantined' : record.process === null ? 'unverified' : 'held', label: null });
514
+ this.host.changed();
515
+ void this.persist(record).catch(() => this.host.notify('Native record persistence unavailable'));
516
+ }
517
+ async opening(work) {
518
+ if (this.closed || this.restoring || this.host.isRestoring?.())
519
+ throw new Error('Desktop closed or restoring');
520
+ this.openings++;
521
+ try {
522
+ return await work();
523
+ }
524
+ catch (error) {
525
+ if (error instanceof DailyError)
526
+ throw error;
527
+ throw new Error(safeDailyMessage(error));
528
+ }
529
+ finally {
530
+ this.openings--;
531
+ }
532
+ }
533
+ async interactive(tool, cwd, saved, target) {
534
+ return this.opening(async () => {
535
+ const provisionalId = saved?.paneId ?? 0x80000000 + Math.floor(Math.random() * 0x7fffffff);
536
+ const record = saved ? rebuildNativeLaunch(saved) : await this.record(provisionalId, tool, 'interactive', cwd);
537
+ await this.version(record, !!saved);
538
+ // A native ZTC pane is one the person types into, on their own profile: it starts on the route that profile saved
539
+ // for new panes, as any new ZTC pane does. Only delegated ZTC is Router-only (recipes.ts).
540
+ if (record.launch.tool === 'ztc')
541
+ record.launch.args = [...record.launch.args, ...newZtcPaneRouteArgs()];
542
+ let lease = await this.lease(record, !saved);
543
+ let accepted = false;
544
+ let dispatched = false;
545
+ let launch;
546
+ try {
547
+ const token = generateToken();
548
+ const launcherEnv = { ...(this.host.env ?? process.env), ZTC_CONFIG_DIR: this.configRoot, ...(tool === 'ztc' ? { ZTC_SKILL_PATHS: (await this.skillRoots()).join(delimiter) } : {}) };
549
+ launch = await prepareNativeLauncher(this.directory, record, { socket: this.control.socketPath, token, publicKey: this.control.publicKey, rendererPid: this.host.transport.launcherParentPid?.() ?? undefined }, launcherEnv, !!saved);
550
+ if (this.closed)
551
+ throw new Error('Desktop closed');
552
+ const requestId = randomUUID();
553
+ const event = await this.request({ type: 'create_pane', request_id: requestId, command: launch.command, args: launch.args, cwd: record.launch.cwd,
554
+ env: launch.env, pane_type: 'process', title: `${tool} interactive`, ...(target === undefined ? {} : { target }) }, event => event.type === 'pane_created' && event.request_id === requestId, () => { dispatched = true; });
555
+ if (event.type !== 'pane_created')
556
+ throw new Error('Native pane unavailable');
557
+ accepted = true;
558
+ record.paneId = event.pane_id;
559
+ lease = await bindLeasePane(lease, record.paneId, this.leaseOptions());
560
+ await this.store.registerParent(record, token);
561
+ const view = await readLease(record.launch.worktree, this.leaseOptions());
562
+ if (view)
563
+ this.store.setLease(record.paneId, view);
564
+ this.live.set(record.paneId, { record, lease, pidfile: launch.pidfile, started: true, lastHeartbeat: 0 });
565
+ record.outcome.stopState = 'running';
566
+ this.publish(record);
567
+ this.pendingIds.delete(record.paneId);
568
+ }
569
+ catch (error) {
570
+ if (launch)
571
+ cleanupNativeLauncherCredentials(launch.pidfile);
572
+ if (accepted || dispatched && !(error instanceof NativeRendererRefusal))
573
+ await releaseOnExit(lease, this.leaseOptions()).catch(() => { });
574
+ else
575
+ await releaseUnstartedLease(lease, this.leaseOptions()).catch(() => { });
576
+ throw error;
577
+ }
578
+ });
579
+ }
580
+ async openDelegated(request, human = false) {
581
+ return this.opening(async () => {
582
+ if (this.closed)
583
+ throw new Error('Desktop closed');
584
+ const cwd = request.worktree === 'new' ? await this.isolate(this.host.cwd()) : request.worktree;
585
+ const paneId = await this.placeholder();
586
+ let acquired = null;
587
+ try {
588
+ this.host.transport.send({ type: 'set_pane_window', pane_id: paneId, window_id: this.childWindow });
589
+ this.host.transport.send({ type: 'focus_pane', pane_id: request.parentPaneId ?? 0 });
590
+ const record = await this.record(paneId, request.tool, 'delegated', cwd);
591
+ record.launch.task = request.task;
592
+ await this.version(record);
593
+ if (request.tool === 'ztc')
594
+ await ensureDelegatedProfile(this.configRoot, this.host.env, await this.skillRoots());
595
+ if (request.tool === 'codex') {
596
+ record.launch.policy = { profileName: 'desktop-codex', permissionProfile: 'read_only', capabilities: { file_read: true, file_write: false, shell_exec: true },
597
+ approvalRequiredCapabilities: [], sandboxBackend: 'codex', sandboxEnforcement: 'os', sandboxRequired: true, brokerUrl: null,
598
+ outputSink: join(this.directory, `result-${paneId}.json`), schemaId: 'fixture-count-v1', schemaHash: schemaRegistry['fixture-count-v1'].hash, adapterVersion: 'dd-adapter-1', policyHash: '' };
599
+ record.launch.policy.policyHash = policyHash(record.launch.policy);
600
+ }
601
+ let launch = request.tool === 'ztc' ? await buildDelegatedZtcLaunch(record, { configRoot: this.configRoot, parentEnv: this.host.env, brokerUrl: this.broker.url,
602
+ artifactPath: join(this.directory, `result-${paneId}.json`), approvalToken: this.broker.issueChild(paneId), skillRoots: await this.skillRoots() }) : null;
603
+ const lease = await this.lease(record, human);
604
+ acquired = lease;
605
+ if (launch && launch.cwd !== record.launch.cwd)
606
+ launch = await buildDelegatedZtcLaunch(record, { configRoot: this.configRoot, parentEnv: this.host.env, brokerUrl: this.broker.url, artifactPath: launch.artifactPath, approvalToken: this.broker.issueChild(paneId), skillRoots: await this.skillRoots() });
607
+ if (this.closed || this.cancelledOpenings.has(paneId))
608
+ throw new Error('Native launch cancelled');
609
+ const live = { record, lease, pidfile: null, started: false, lastHeartbeat: 0 };
610
+ this.live.set(paneId, live);
611
+ this.pendingIds.delete(paneId);
612
+ let started = false;
613
+ let cancelled = false;
614
+ const cancel = async () => { if (started || cancelled)
615
+ return; cancelled = true; await this.closePane(paneId); };
616
+ return { record, lease: { lease, state: 'unverified', label: null }, broker: this.broker, cancel,
617
+ start: () => {
618
+ if (cancelled || live.cancelRequested || this.closed || this.live.get(paneId) !== live) {
619
+ if (this.store.hasRecord(paneId))
620
+ this.store.removeChild(paneId);
621
+ void cancel().catch(() => { });
622
+ return;
623
+ }
624
+ if (started)
625
+ return;
626
+ started = true;
627
+ live.completion = this.run(live, launch).catch(() => this.failed(live)).finally(() => { delete live.completion; });
628
+ } };
629
+ }
630
+ catch (error) {
631
+ if (acquired) {
632
+ if (acquired.usedWritable)
633
+ await releaseOnExit(acquired, this.leaseOptions()).catch(() => { });
634
+ else
635
+ await releaseUnstartedReadLease(acquired, this.leaseOptions()).catch(() => { });
636
+ }
637
+ this.pendingIds.delete(paneId);
638
+ this.live.delete(paneId);
639
+ this.broker.revokeChild(paneId);
640
+ this.host.transport.send({ type: 'close_pane', pane_id: paneId });
641
+ throw error;
642
+ }
643
+ finally {
644
+ this.cancelledOpenings.delete(paneId);
645
+ }
646
+ });
647
+ }
648
+ async skillRoots() { return delegatedSkillRoots(this.host.env?.HOME ?? homedir(), this.host.delegatedSkillRoots?.() ?? []); }
649
+ failed(live) {
650
+ if (this.closed)
651
+ return;
652
+ const observation = { state: 'failed', approvalState: 'denied', errorClass: 'launch_refused', eventCount: 0, tokens: null, projection: { ok: false, reason: 'empty_sink' } };
653
+ this.publish(live.record, observation);
654
+ this.host.notify('Native child launch refused');
655
+ }
656
+ async run(live, launch, resume = false, prompt) {
657
+ if (this.closed)
658
+ throw new Error('Desktop closed');
659
+ live.started = true;
660
+ live.record.outcome.stopState = 'running';
661
+ live.record.outcome.exit = null;
662
+ live.record.process = null;
663
+ this.publish(live.record, { state: 'running', approvalState: 'none', errorClass: 'none', eventCount: 0, tokens: null, projection: { ok: false, reason: 'empty_sink' } });
664
+ const owner = { desktopOwnerId: this.ownerId, revision: this.store.identityFor(live.record.paneId).revision };
665
+ const onRawLines = (lines) => { if (this.closed || live.cancelRequested)
666
+ return; this.host.transport.send({ type: 'append_pane_lines', pane_id: live.record.paneId, lines: lines.slice(-500).map(line => line.slice(0, 4096)), trim: 500 }); };
667
+ const onUpdate = (record, observation) => {
668
+ if (observation.state === 'result_available')
669
+ return;
670
+ this.publish(record, observation);
671
+ if (live.cancelRequested && record.process !== null && record.outcome.stopState === 'running')
672
+ void this.stop(record.paneId, false).catch(() => { });
673
+ };
674
+ const record = live.record;
675
+ let admitted = false;
676
+ const beforeSpawn = () => { admitted = !this.closed && live.started; return admitted; };
677
+ try {
678
+ const result = launch ? await runZtcHeadless(record, launch, { owner, onRawLines, onUpdate, beforeSpawn })
679
+ : await runCodexExec(record, { owner, env: this.host.env, resume, prompt, onRawLines, onUpdate, beforeSpawn });
680
+ if (!this.closed) {
681
+ live.record = structuredClone(record);
682
+ await this.release(live);
683
+ this.publish(record, result);
684
+ }
685
+ }
686
+ catch (error) {
687
+ if (!admitted) {
688
+ live.started = false;
689
+ live.record.outcome.stopState = 'leader_exited';
690
+ if (live.lease.usedWritable)
691
+ await this.release(live);
692
+ else {
693
+ await this.queueLease(live, () => releaseUnstartedReadLease(live.lease, this.leaseOptions()));
694
+ this.store.setLease(live.record.paneId, null);
695
+ this.broker.revokeChild(live.record.paneId);
696
+ }
697
+ }
698
+ throw error;
699
+ }
700
+ }
701
+ async queueLease(live, action) {
702
+ const queued = (this.leaseQueues.get(live) ?? Promise.resolve()).then(action);
703
+ this.leaseQueues.set(live, queued.catch(() => { }));
704
+ await queued;
705
+ }
706
+ async release(live) {
707
+ await this.queueLease(live, async () => {
708
+ const current = await readLease(live.record.launch.worktree, this.leaseOptions());
709
+ if (current && current.lease.acquiredAt !== live.lease.acquiredAt) {
710
+ this.store.setLease(live.record.paneId, current);
711
+ this.label(live.record, current);
712
+ this.broker.revokeChild(live.record.paneId);
713
+ return;
714
+ }
715
+ if (live.record.identity.state === 'bound' && live.lease.ownerSessionId === null)
716
+ live.lease = await bindLeaseSession(live.lease, live.record.identity.canonicalId, this.leaseOptions());
717
+ if (live.record.process && live.lease.leaderPid === null && live.lease.ownerState !== 'exited')
718
+ live.lease = await heartbeat(live.lease, this.leaseOptions(), live.record.process);
719
+ if (live.lease.ownerState !== 'exited')
720
+ live.lease = await releaseOnExit(live.lease, this.leaseOptions());
721
+ const view = await readLease(live.record.launch.worktree, this.leaseOptions());
722
+ if (view)
723
+ this.store.setLease(live.record.paneId, view);
724
+ this.broker.revokeChild(live.record.paneId);
725
+ this.label(live.record, view);
726
+ if (live.pidfile)
727
+ cleanupNativeLauncherCredentials(live.pidfile);
728
+ });
729
+ }
730
+ async action(paneId, work) {
731
+ if (this.closed || this.restoring || this.host.isRestoring?.() || this.actions.has(paneId))
732
+ throw new Error('Native action pending or desktop closed');
733
+ this.actions.add(paneId);
734
+ try {
735
+ return await work();
736
+ }
737
+ catch (error) {
738
+ if (error instanceof DailyError)
739
+ throw error;
740
+ throw new Error(safeDailyMessage(error));
741
+ }
742
+ finally {
743
+ this.actions.delete(paneId);
744
+ }
745
+ }
746
+ async adopt(paneId, parentPaneId) {
747
+ return this.action(paneId, async () => {
748
+ const record = this.store.getRecord(paneId);
749
+ const view = await readLease(record.launch.worktree, this.leaseOptions());
750
+ if (record.launchOwnerId !== view?.lease.desktopOwnerId || record.leaseAcquiredAt !== view?.lease.acquiredAt || record.controlOwnerPid === undefined || record.controlOwnerStartMs === undefined)
751
+ throw new DailyError('lease_refused');
752
+ if (record.launchOwnerId !== this.ownerId || record.controlOwnerPid !== process.pid || record.controlOwnerStartMs !== this.ownerStartMs) {
753
+ const start = await observeProcessStart(record.controlOwnerPid);
754
+ if (start !== null && Math.abs(start - record.controlOwnerStartMs) <= 2000)
755
+ throw new DailyError('lease_refused');
756
+ }
757
+ if (!record.provenance || !record.provenance.shellPid || !record.provenance.leaderPid)
758
+ throw new DailyError('lease_refused');
759
+ if (!view || record.provenance.leaderPid !== view.lease.leaderPid || record.provenance.leaderStartMs !== view.lease.leaderStartMs)
760
+ throw new DailyError('lease_refused');
761
+ const previous = { shellPid: record.provenance.shellPid, shellStartMs: record.provenance.shellStartMs, exitCode: null,
762
+ process: { leaderPid: view.lease.leaderPid, leaderStartMs: view.lease.leaderStartMs, pgid: view.lease.pgid, paneId, desktopOwnerId: view.lease.desktopOwnerId, revision: this.store.identityFor(paneId).revision } };
763
+ const admission = await observeLauncher(record.provenance.pidfile, { ...this.store.identityFor(paneId), desktopOwnerId: this.ownerId, provenance: record.provenance }, previous).catch(() => null);
764
+ if (!admission || admission.process?.leaderPid !== record.provenance.leaderPid)
765
+ throw new DailyError('lease_refused');
766
+ if (view && !view.lease.usedWritable && view.lease.ownerState === 'exited'
767
+ && view.lease.ownerSessionId === record.identity.canonicalId && view.lease.ownerPaneId === paneId) {
768
+ const lease = view.lease;
769
+ if (lease.leaderPid === null || lease.pgid === null || await observeProcessStart(lease.leaderPid) !== null
770
+ || (await groupMembersOf(lease.pgid))?.length !== 0)
771
+ throw new Error('Live lease identity cannot be adopted');
772
+ await validateNativeResume(record, view, async () => resolveDelegatedPolicy(this.configRoot, this.host.env, record.launch.cwd, await this.skillRoots()));
773
+ this.store.adoptChild(paneId, this.store.parentTokenForOwner(parentPaneId));
774
+ record.enrollmentId = this.store.getRecord(paneId).enrollmentId;
775
+ record.process = null;
776
+ this.publish(record);
777
+ this.store.setLease(paneId, view);
778
+ return;
779
+ }
780
+ if (!view || view.state !== 'held' || view.lease.ownerSessionId !== record.identity.canonicalId || view.lease.ownerPaneId !== paneId)
781
+ throw new Error('Live lease identity cannot be adopted');
782
+ let lease = view.lease;
783
+ const identity = { leaderPid: lease.leaderPid, leaderStartMs: lease.leaderStartMs, pgid: lease.pgid, paneId, desktopOwnerId: lease.desktopOwnerId, revision: this.store.identityFor(paneId).revision };
784
+ if (await validateIdentity(identity) !== 'valid')
785
+ throw new Error('Live process identity cannot be adopted');
786
+ if (lease.desktopOwnerId !== this.ownerId) {
787
+ if (!/^[a-zA-Z0-9_-]{1,64}$/.test(lease.desktopOwnerId))
788
+ throw new Error('Previous desktop owner is unverified');
789
+ lease = await adoptLeaseOwner(lease, this.ownerId, 'desktop_human', this.leaseOptions());
790
+ }
791
+ this.store.adoptChild(paneId, this.store.parentTokenForOwner(parentPaneId));
792
+ record.enrollmentId = this.store.getRecord(paneId).enrollmentId;
793
+ record.process = { ...identity, desktopOwnerId: this.ownerId };
794
+ record.outcome.stopState = 'running';
795
+ record.outcome.exit = null;
796
+ const existing = this.live.get(paneId);
797
+ if (existing) {
798
+ existing.record = record;
799
+ existing.lease = lease;
800
+ }
801
+ else
802
+ this.live.set(paneId, { record, lease, pidfile: null, started: true, lastHeartbeat: 0 });
803
+ this.publish(record);
804
+ this.store.setLease(paneId, { ...view, lease });
805
+ });
806
+ }
807
+ async stop(paneId, human = true) {
808
+ return this.action(paneId, async () => {
809
+ const live = this.live.get(paneId);
810
+ if (!live)
811
+ throw new Error('Native pane not found');
812
+ if (live.record.outcome.stopState === 'leader_exited')
813
+ return live.record.outcome;
814
+ await this.queueLease(live, async () => {
815
+ const current = await readLease(live.record.launch.worktree, this.leaseOptions());
816
+ if (current?.lease.acquiredAt === live.lease.acquiredAt) {
817
+ live.lease = await markLeaseUnverified(live.lease, this.leaseOptions());
818
+ const view = await readLease(live.record.launch.worktree, this.leaseOptions());
819
+ if (view)
820
+ this.store.setLease(paneId, view);
821
+ }
822
+ });
823
+ if (live.record.process === null)
824
+ live.started = false;
825
+ const outcome = await stopNativePane(live.record, live.pidfile, live.observation, { confirmKill: async () => human && await this.host.select(`Kill pane ${paneId}?`, [{ value: 'deny', label: 'Keep running' }, { value: 'kill', label: 'Send SIGKILL' }]) === 'kill' });
826
+ live.record.outcome = outcome;
827
+ this.publish(live.record);
828
+ if (outcome.stopState === 'leader_exited')
829
+ await this.release(live);
830
+ this.host.notify(`Pane ${paneId}: ${outcome.stopState}; observed survivors ${outcome.survivors.join(', ') || 'none observed'}`);
831
+ return outcome;
832
+ });
833
+ }
834
+ async resume(paneId, prompt) {
835
+ return this.action(paneId, async () => {
836
+ const record = this.store.getRecord(paneId);
837
+ const view = this.store.leaseFor(paneId);
838
+ const currentLease = await readLease(record.launch.worktree, this.leaseOptions());
839
+ if (view && currentLease?.lease.acquiredAt !== view.lease.acquiredAt)
840
+ throw new DailyError('lease_refused');
841
+ if (this.live.get(paneId)?.started && record.outcome.stopState !== 'leader_exited')
842
+ throw new Error('Native pane still active');
843
+ if (!this.store.leaseFor(paneId))
844
+ throw new DailyError('lease_refused');
845
+ if (record.launch.tool === 'ztc' && record.launch.mode === 'delegated')
846
+ await ensureDelegatedProfile(this.configRoot, this.host.env, await this.skillRoots());
847
+ await validateNativeResume(record, view, async () => resolveDelegatedPolicy(this.configRoot, this.host.env, record.launch.cwd, await this.skillRoots()));
848
+ if (record.launch.mode === 'interactive') {
849
+ await this.interactive(record.launch.tool, record.launch.cwd, record);
850
+ return;
851
+ }
852
+ if (record.launch.tool === 'ztc' && prompt === undefined) {
853
+ const answer = await this.host.input(`Continuation prompt for pane ${paneId}`);
854
+ if (!answer?.trim())
855
+ throw new DailyError('invalid');
856
+ prompt = answer;
857
+ }
858
+ if (record.launch.tool === 'codex')
859
+ await this.version(record, true);
860
+ const launch = record.launch.tool === 'ztc' ? await buildDelegatedZtcLaunch(record, { configRoot: this.configRoot, parentEnv: this.host.env, artifactPath: record.launch.policy.outputSink,
861
+ brokerUrl: this.broker.url, approvalToken: this.broker.issueChild(paneId), skillRoots: await this.skillRoots(), resume: true, prompt }) : null;
862
+ const lease = await this.lease(record, false);
863
+ const live = { record, lease, pidfile: null, started: false, lastHeartbeat: 0 };
864
+ this.live.set(paneId, live);
865
+ if (record.launch.tool === 'codex' && prompt === undefined && record.launch.task === undefined)
866
+ prompt = 'Continue this exact session. Return the final answer using fixture-count-v1. Write nothing.';
867
+ live.completion = this.run(live, launch, true, prompt).catch(() => this.failed(live)).finally(() => { delete live.completion; });
868
+ });
869
+ }
870
+ async poll() {
871
+ if (this.polling || this.closed)
872
+ return;
873
+ this.polling = true;
874
+ try {
875
+ if (Date.now() - this.lastAuth >= 60000)
876
+ void this.refreshRouter();
877
+ for (const live of this.live.values()) {
878
+ if (live.cleanupUntil !== undefined) {
879
+ if (Date.now() <= live.cleanupUntil && live.pidfile && live.record.provenance)
880
+ await terminateLauncherGroup(live.pidfile, live.record.provenance).catch(() => false);
881
+ continue;
882
+ }
883
+ if (!live.started || live.record.outcome.stopState === 'leader_exited')
884
+ continue;
885
+ if (live.pidfile) {
886
+ try {
887
+ const observation = await observeLauncher(live.pidfile, { paneId: live.record.paneId, desktopOwnerId: this.ownerId, revision: this.store.identityFor(live.record.paneId).revision, provenance: live.record.provenance }, live.observation);
888
+ if (observation) {
889
+ live.observation = observation;
890
+ if (observation.process && live.record.process === null) {
891
+ live.record.process = observation.process;
892
+ this.publish(live.record);
893
+ this.store.admitParent(live.record.paneId);
894
+ live.admitted = true;
895
+ }
896
+ if (observation.exitCode !== null) {
897
+ live.record.outcome = { ...live.record.outcome, exit: { code: observation.exitCode, signal: null }, stopState: 'leader_exited' };
898
+ this.publish(live.record);
899
+ await this.release(live);
900
+ continue;
901
+ }
902
+ }
903
+ }
904
+ catch {
905
+ live.record.outcome.stopState = 'identity_lost';
906
+ this.store.revokeParent(live.record.paneId);
907
+ if (!live.admitted) {
908
+ live.started = false;
909
+ live.cleanupUntil = (live.record.provenance?.expiresAt ?? Date.now()) + 3500;
910
+ this.failed(live);
911
+ if (live.pidfile && live.record.provenance)
912
+ await terminateLauncherGroup(live.pidfile, live.record.provenance).catch(() => false);
913
+ this.host.transport.send({ type: 'close_pane', pane_id: live.record.paneId });
914
+ await this.release(live);
915
+ continue;
916
+ }
917
+ this.publish(live.record);
918
+ }
919
+ if (live.record.process && await observeProcessStart(live.record.process.leaderPid) === null) {
920
+ live.record.outcome.stopState = 'identity_lost';
921
+ this.store.revokeParent(live.record.paneId);
922
+ this.publish(live.record);
923
+ }
924
+ }
925
+ await this.queueLease(live, async () => {
926
+ if (live.lease.ownerState === 'exited')
927
+ return;
928
+ const current = await readLease(live.record.launch.worktree, this.leaseOptions());
929
+ if (current && current.lease.acquiredAt !== live.lease.acquiredAt) {
930
+ this.store.setLease(live.record.paneId, current);
931
+ this.label(live.record, current);
932
+ return;
933
+ }
934
+ if (live.record.identity.state === 'bound' && live.lease.ownerSessionId === null)
935
+ live.lease = await bindLeaseSession(live.lease, live.record.identity.canonicalId, this.leaseOptions());
936
+ if (live.record.process && Date.now() - live.lastHeartbeat > 10000) {
937
+ const start = await observeProcessStart(live.record.process.leaderPid);
938
+ const status = await exec('/bin/ps', ['-p', String(live.record.process.leaderPid), '-o', 'state=']).then(result => result.stdout.trim()).catch(() => '');
939
+ if (!status.startsWith('T') && start !== null && Math.abs(start - live.record.process.leaderStartMs) <= 2000) {
940
+ live.lease = await heartbeat(live.lease, this.leaseOptions(), live.record.process);
941
+ live.lastHeartbeat = Date.now();
942
+ const view = await readLease(live.record.launch.worktree, this.leaseOptions());
943
+ if (view) {
944
+ this.store.setLease(live.record.paneId, view);
945
+ this.label(live.record, view);
946
+ }
947
+ }
948
+ else {
949
+ const view = await readLease(live.record.launch.worktree, this.leaseOptions());
950
+ if (view) {
951
+ this.store.setLease(live.record.paneId, view);
952
+ this.label(live.record, view);
953
+ }
954
+ }
955
+ }
956
+ }).catch(() => { this.label(live.record, { lease: live.lease, state: 'unverified', label: null }); });
957
+ }
958
+ const approval = this.broker.pending[0];
959
+ if (approval && !this.dialog) {
960
+ this.dialog = true;
961
+ void answerDesktopApproval(this.broker, (title, options) => this.host.select(title, options))
962
+ .catch(() => { }).finally(() => { this.dialog = false; });
963
+ }
964
+ }
965
+ catch {
966
+ this.host.notify('Native ownership observation unavailable');
967
+ }
968
+ finally {
969
+ this.polling = false;
970
+ }
971
+ }
972
+ async closePane(paneId, rendererClosed = false) {
973
+ const live = this.live.get(paneId);
974
+ if (live?.closing)
975
+ return live.closing;
976
+ const closing = async () => {
977
+ if (live) {
978
+ live.cancelRequested = true;
979
+ if (!live.started && live.completion === undefined) {
980
+ await this.queueLease(live, async () => {
981
+ const current = await readLease(live.record.launch.worktree, this.leaseOptions());
982
+ if (current) {
983
+ if (live.lease.usedWritable)
984
+ await releaseOnExit(live.lease, this.leaseOptions());
985
+ else
986
+ await releaseUnstartedReadLease(live.lease, this.leaseOptions());
987
+ }
988
+ if (this.store.hasRecord(paneId))
989
+ this.store.setLease(paneId, null);
990
+ });
991
+ }
992
+ if (live.record.process === null)
993
+ live.started = false;
994
+ else if (live.record.outcome.stopState !== 'leader_exited') {
995
+ const outcome = await this.stop(paneId, false);
996
+ if (outcome.stopState !== 'leader_exited')
997
+ throw new DailyError('launch_refused');
998
+ }
999
+ await live.completion;
1000
+ if (live.record.process !== null && live.record.outcome.stopState !== 'leader_exited')
1001
+ throw new DailyError('launch_refused');
1002
+ }
1003
+ if (!rendererClosed)
1004
+ this.host.transport.send({ type: 'close_pane', pane_id: paneId });
1005
+ this.live.delete(paneId);
1006
+ };
1007
+ const pending = closing();
1008
+ if (live)
1009
+ live.closing = pending;
1010
+ try {
1011
+ await pending;
1012
+ }
1013
+ finally {
1014
+ if (live)
1015
+ delete live.closing;
1016
+ }
1017
+ }
1018
+ paneClosed(paneId) {
1019
+ this.store.revokeParent(paneId);
1020
+ const pidfile = this.live.get(paneId)?.pidfile;
1021
+ if (pidfile)
1022
+ cleanupNativeLauncherCredentials(pidfile);
1023
+ if (this.pendingIds.has(paneId))
1024
+ this.cancelledOpenings.add(paneId);
1025
+ if (this.live.get(paneId)?.record.launch.mode === 'delegated')
1026
+ void this.closePane(paneId, true).then(() => { if (this.store.hasRecord(paneId))
1027
+ this.store.removeChild(paneId); }).catch(() => this.host.notify('Native worker could not be stopped; use Stop in Status'));
1028
+ }
1029
+ async close() {
1030
+ if (this.closed)
1031
+ return;
1032
+ this.closed = true;
1033
+ this.authAbort.abort();
1034
+ if (this.timer)
1035
+ clearInterval(this.timer);
1036
+ for (const paneId of this.store.parentPaneIdsForOwner())
1037
+ this.store.revokeParent(paneId);
1038
+ for (const live of this.live.values())
1039
+ if (live.pidfile)
1040
+ cleanupNativeLauncherCredentials(live.pidfile);
1041
+ while (this.polling)
1042
+ await delay(10);
1043
+ await Promise.all([...this.live.values()].map(live => this.leaseQueues.get(live) ?? Promise.resolve()));
1044
+ await this.control?.close();
1045
+ await this.broker?.close();
1046
+ await Promise.all(this.persistQueues.values());
1047
+ }
1048
+ }