@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.
- package/README.md +222 -6
- package/bin/zmux-darwin-arm64 +0 -0
- package/bin/ztc-audio-darwin-arm64 +0 -0
- package/bin/ztc-capture-darwin-arm64 +0 -0
- package/bin/ztc-tui-darwin-arm64 +0 -0
- package/bin/zterm-darwin-arm64 +2 -2
- package/dist/agent/agent.d.ts +17 -0
- package/dist/agent/agent.js +77 -4
- package/dist/agent/backends/index.js +5 -3
- package/dist/agent/backends/zrouter_stream.js +8 -4
- package/dist/agent/commands/goal.d.ts +2 -0
- package/dist/agent/commands/goal.js +7 -2
- package/dist/agent/factory.d.ts +2 -0
- package/dist/agent/factory.js +1 -0
- package/dist/agent/request_encoder.d.ts +2 -1
- package/dist/agent/request_encoder.js +4 -3
- package/dist/agent/runtime/policy.d.ts +1 -0
- package/dist/agent/runtime/policy.js +23 -3
- package/dist/agent/runtime/tool_runtime.js +13 -12
- package/dist/agent/subagent.js +2 -1
- package/dist/agent/tools/ask_user.d.ts +1 -1
- package/dist/agent/tools/ask_user.js +15 -8
- package/dist/agent/tools/pane.d.ts +6 -0
- package/dist/agent/tools/pane.js +18 -4
- package/dist/agent/tools/search.js +1 -1
- package/dist/agent/tools/sim_domain_tools.d.ts +4 -0
- package/dist/agent/tools/sim_domain_tools.js +28 -2
- package/dist/agent/tools/types.d.ts +3 -0
- package/dist/app/correlated_turn.d.ts +14 -0
- package/dist/app/correlated_turn.js +78 -0
- package/dist/app/prompt_turn.d.ts +2 -1
- package/dist/app/prompt_turn.js +15 -2
- package/dist/app/session_manager.d.ts +17 -11
- package/dist/app/session_manager.js +74 -30
- package/dist/app/tool_callbacks.d.ts +1 -1
- package/dist/app/workspace_layout_controller.d.ts +21 -2
- package/dist/app/workspace_layout_controller.js +61 -10
- package/dist/app/workspace_monitor.js +67 -7
- package/dist/app/workspace_presets.d.ts +1 -0
- package/dist/app/workspace_presets.js +2 -2
- package/dist/cli.js +6 -2
- package/dist/cli_args.js +1 -0
- package/dist/cli_main.js +48 -2
- package/dist/cli_ratatui.d.ts +56 -8
- package/dist/cli_ratatui.js +689 -109
- package/dist/config/permissions.js +1 -1
- package/dist/config/router_required.d.ts +11 -0
- package/dist/config/router_required.js +23 -0
- package/dist/config/types.d.ts +5 -0
- package/dist/config.d.ts +3 -1
- package/dist/config.js +66 -49
- package/dist/desktop/daily/broker.d.ts +26 -0
- package/dist/desktop/daily/broker.js +140 -0
- package/dist/desktop/daily/codex_config.d.ts +2 -0
- package/dist/desktop/daily/codex_config.js +119 -0
- package/dist/desktop/daily/codex_exec_adapter.d.ts +42 -0
- package/dist/desktop/daily/codex_exec_adapter.js +251 -0
- package/dist/desktop/daily/control_client.d.ts +4 -0
- package/dist/desktop/daily/control_client.js +214 -0
- package/dist/desktop/daily/control_credentials.d.ts +15 -0
- package/dist/desktop/daily/control_credentials.js +85 -0
- package/dist/desktop/daily/control_hello.d.ts +10 -0
- package/dist/desktop/daily/control_hello.js +6 -0
- package/dist/desktop/daily/control_protocol.d.ts +39 -0
- package/dist/desktop/daily/control_protocol.js +4 -0
- package/dist/desktop/daily/control_schema.d.ts +9 -0
- package/dist/desktop/daily/control_schema.js +25 -0
- package/dist/desktop/daily/control_server.d.ts +44 -0
- package/dist/desktop/daily/control_server.js +286 -0
- package/dist/desktop/daily/daily_store.d.ts +71 -0
- package/dist/desktop/daily/daily_store.js +290 -0
- package/dist/desktop/daily/delegated_ztc_contract.d.ts +37 -0
- package/dist/desktop/daily/delegated_ztc_contract.js +90 -0
- package/dist/desktop/daily/desktop_wiring.d.ts +112 -0
- package/dist/desktop/daily/desktop_wiring.js +1048 -0
- package/dist/desktop/daily/enrollment.d.ts +74 -0
- package/dist/desktop/daily/enrollment.js +77 -0
- package/dist/desktop/daily/file_facts.d.ts +2 -0
- package/dist/desktop/daily/file_facts.js +41 -0
- package/dist/desktop/daily/lease.d.ts +57 -0
- package/dist/desktop/daily/lease.js +332 -0
- package/dist/desktop/daily/legacy_codex_homes.d.ts +1 -0
- package/dist/desktop/daily/legacy_codex_homes.js +26 -0
- package/dist/desktop/daily/native_pane_launcher.d.ts +31 -0
- package/dist/desktop/daily/native_pane_launcher.js +226 -0
- package/dist/desktop/daily/native_records.d.ts +13 -0
- package/dist/desktop/daily/native_records.js +81 -0
- package/dist/desktop/daily/native_status.d.ts +4 -0
- package/dist/desktop/daily/native_status.js +28 -0
- package/dist/desktop/daily/native_tool.d.ts +134 -0
- package/dist/desktop/daily/native_tool.js +91 -0
- package/dist/desktop/daily/owner_files.d.ts +3 -0
- package/dist/desktop/daily/owner_files.js +88 -0
- package/dist/desktop/daily/owner_seals.d.ts +9 -0
- package/dist/desktop/daily/owner_seals.js +56 -0
- package/dist/desktop/daily/process_identity.d.ts +13 -0
- package/dist/desktop/daily/process_identity.js +137 -0
- package/dist/desktop/daily/profile_bootstrap.d.ts +60 -0
- package/dist/desktop/daily/profile_bootstrap.js +194 -0
- package/dist/desktop/daily/raw_receipts.d.ts +1 -0
- package/dist/desktop/daily/raw_receipts.js +18 -0
- package/dist/desktop/daily/recipes.d.ts +36 -0
- package/dist/desktop/daily/recipes.js +177 -0
- package/dist/desktop/daily/router_state.d.ts +33 -0
- package/dist/desktop/daily/router_state.js +39 -0
- package/dist/desktop/daily/schema_registry.d.ts +19 -0
- package/dist/desktop/daily/schema_registry.js +71 -0
- package/dist/desktop/daily/source_baseline.d.ts +13 -0
- package/dist/desktop/daily/source_baseline.js +44 -0
- package/dist/desktop/daily/status_restore.d.ts +9 -0
- package/dist/desktop/daily/status_restore.js +114 -0
- package/dist/desktop/daily/summary.d.ts +59 -0
- package/dist/desktop/daily/summary.js +75 -0
- package/dist/desktop/daily/worker_provenance.d.ts +2 -0
- package/dist/desktop/daily/worker_provenance.js +18 -0
- package/dist/desktop/daily/worker_stop.d.ts +2 -0
- package/dist/desktop/daily/worker_stop.js +26 -0
- package/dist/desktop/daily/ztc_headless_adapter.d.ts +40 -0
- package/dist/desktop/daily/ztc_headless_adapter.js +194 -0
- package/dist/domain.d.ts +1 -1
- package/dist/domain.js +1 -1
- package/dist/events.d.ts +23 -1
- package/dist/headless.d.ts +9 -0
- package/dist/headless.js +161 -26
- package/dist/headless_approval.d.ts +29 -0
- package/dist/headless_approval.js +69 -0
- package/dist/headless_cli.js +2 -0
- package/dist/headless_cli_args.d.ts +4 -0
- package/dist/headless_cli_args.js +5 -0
- package/dist/library.d.ts +20 -0
- package/dist/library.js +66 -12
- package/dist/mcp/client.d.ts +16 -1
- package/dist/mcp/client.js +11 -5
- package/dist/mcp/registry.d.ts +3 -1
- package/dist/mcp/registry.js +10 -1
- package/dist/panes/pane_registry.js +14 -3
- package/dist/panes/types.d.ts +7 -1
- package/dist/panes/ztc_launch.d.ts +5 -0
- package/dist/panes/ztc_launch.js +30 -14
- package/dist/session.d.ts +6 -3
- package/dist/session.js +21 -2
- package/dist/simulation/domain_types.d.ts +2 -0
- package/dist/simulation/domains/loader.d.ts +7 -1
- package/dist/simulation/domains/loader.js +33 -1
- package/dist/simulation/living/context.d.ts +19 -19
- package/dist/simulation/living/definition.d.ts +2 -2
- package/dist/simulation/living/frame.d.ts +1 -1
- package/dist/simulation/living/open-world.d.ts +3 -3
- package/dist/simulation/living/types.d.ts +24 -24
- package/dist/simulation/toolkit/dynamic_state.d.ts +1 -1
- package/dist/skills/bundled/init-context/SKILL.md +16 -0
- package/dist/skills/registry.js +7 -3
- package/dist/tools.d.ts +6 -0
- package/dist/tools.js +14 -0
- package/dist/types.d.ts +30 -0
- package/dist/ui/ratatui/mux_persistence.d.ts +3 -1
- package/dist/ui/ratatui/mux_persistence.js +9 -2
- package/dist/ui/ratatui/pane_credential_broker.d.ts +8 -4
- package/dist/ui/ratatui/pane_credential_broker.js +26 -11
- package/dist/ui/ratatui/pane_relay.d.ts +2 -0
- package/dist/ui/ratatui/process.d.ts +6 -0
- package/dist/ui/ratatui/process.js +104 -6
- package/dist/ui/ratatui/protocol.d.ts +13 -0
- package/dist/ui/ratatui/protocol.js +1 -0
- package/dist/utils/compaction.js +6 -4
- package/dist/utils/subprocess_env.js +2 -0
- package/dist/web/browser_events.d.ts +10 -0
- package/dist/web/browser_events.js +9 -0
- package/dist/web/mirror_stream.d.ts +17 -5
- package/dist/web/mirror_stream.js +105 -13
- package/dist/web/pane_credentials.d.ts +6 -3
- package/dist/web/pane_credentials.js +20 -12
- package/dist/web/pane_registry.js +1 -0
- package/dist/workspace_agent.d.ts +2 -1
- package/dist/workspace_agent.js +7 -1
- package/dist/workspace_collision.d.ts +3 -0
- package/dist/workspace_collision.js +1 -1
- package/dist/workspace_layout.d.ts +3 -2
- package/dist/workspace_layout.js +8 -2
- package/dist/workspace_runtime.d.ts +7 -1
- package/dist/workspace_runtime.js +3 -3
- package/dist/zerg/manifest_builder_tools.js +35 -4
- package/dist/zerg/manifest_validator.js +55 -0
- package/dist/zlm-embed.mjs +261 -116
- package/node_modules/@zerg/model-contracts/README.md +19 -0
- package/node_modules/@zerg/model-contracts/index.js +19 -1
- package/node_modules/@ztc/sim-graph/dist/index.d.ts +1 -0
- package/node_modules/@ztc/sim-graph/dist/index.js +1 -0
- package/node_modules/@ztc/sim-graph/dist/sim_graph.d.ts +351 -0
- package/node_modules/@ztc/sim-graph/dist/sim_graph.js +795 -0
- package/node_modules/@ztc/sim-graph/package.json +37 -0
- package/node_modules/@ztc/sim-graph/src/index.ts +1 -0
- package/node_modules/@ztc/sim-graph/src/sim_graph.ts +1305 -0
- package/package.json +25 -24
- package/packages/model-contracts/README.md +19 -0
- package/packages/model-contracts/index.js +19 -1
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { constants, lstatSync, renameSync } from 'node:fs';
|
|
3
|
+
import { open, unlink, realpath } from 'node:fs/promises';
|
|
4
|
+
import { join, basename, dirname } from 'node:path';
|
|
5
|
+
import { randomUUID, randomBytes, createPublicKey } from 'node:crypto';
|
|
6
|
+
import { homedir } from 'node:os';
|
|
7
|
+
import { promisify } from 'node:util';
|
|
8
|
+
import { buildLaunchArgv, buildResumeArgv } from './recipes.js';
|
|
9
|
+
import { checkoutEntry } from './profile_bootstrap.js';
|
|
10
|
+
import { ownerDirectory, atomicOwnerFile } from './owner_files.js';
|
|
11
|
+
import { DESKTOP_CREDENTIAL_FILE_FLAG, desktopCredentialShimEntry, removeDesktopCredentialSource } from './control_credentials.js';
|
|
12
|
+
import { writePaneCredentialHandoff, removePaneCredentialHandoff, PANE_CREDENTIAL_ENV, ZTC_PANE_CREDENTIAL_REQUEST } from '../../web/pane_credentials.js';
|
|
13
|
+
import { observeProcessStart, processGroupOf, stopSequence, validateIdentity } from './process_identity.js';
|
|
14
|
+
const exec = promisify(execFile);
|
|
15
|
+
const quote = (value) => "'" + value.replaceAll("'", "'\\''") + "'";
|
|
16
|
+
const receipts = new Map();
|
|
17
|
+
const receiptScript = `const fs=require('node:fs'),cp=require('node:child_process'),crypto=require('node:crypto'),path=require('node:path');
|
|
18
|
+
const [file,nonce,shell,leader,phase,code]=process.argv.slice(1);
|
|
19
|
+
const start=pid=>{try{return Date.parse(cp.execFileSync('/bin/ps',['-p',pid,'-o','lstart='],{encoding:'utf8'}).trim())}catch{return null}};
|
|
20
|
+
const value=phase==='start'?{nonce,shellPid:Number(shell),shellStartMs:start(shell),leaderPid:Number(leader),leaderStartMs:start(leader)}:{nonce,code:Number(code)};
|
|
21
|
+
const target=file+(phase==='exit'?'.exit':'');const temp=path.join(path.dirname(target),'.receipt-'+crypto.randomUUID());
|
|
22
|
+
const fd=fs.openSync(temp,'wx',0o600);try{fs.writeFileSync(fd,JSON.stringify(value));fs.fsyncSync(fd)}finally{fs.closeSync(fd)}fs.renameSync(temp,target);
|
|
23
|
+
const info=fs.lstatSync(target);if(!info.isFile()||info.nlink!==1||info.uid!==process.getuid())process.exit(4);`;
|
|
24
|
+
export const LAUNCHER_SCRIPT = 'exec 3<&0; export PATH="$ZTC_DESKTOP_SHIM:$PATH"; nonce=$1; node=$2; receipt=$3; deadline=$4; shift 4; /bin/sh -c \'until test -f "$1.admit"; do if test "$(/bin/date +%s)" -ge "$2"; then exit 4; fi; /bin/sleep 0.02; done; shift 2; exec "$@"\' native "$0" "$deadline" "$@" <&3 3<&- & leader=$!; exec 3<&-; "$node" -e "$receipt" "$0" "$nonce" "$$" "$leader" start || { kill -TERM "$leader"; exit 4; }; wait "$leader"; code=$?; "$node" -e "$receipt" "$0" "$nonce" "$$" "$leader" exit "$code"; exit "$code"';
|
|
25
|
+
async function receiptFile(path) {
|
|
26
|
+
let handle;
|
|
27
|
+
try {
|
|
28
|
+
handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
if (error.code === 'ENOENT')
|
|
32
|
+
return null;
|
|
33
|
+
throw error;
|
|
34
|
+
}
|
|
35
|
+
try {
|
|
36
|
+
const stat = await handle.stat();
|
|
37
|
+
if (!stat.isFile() || stat.nlink !== 1 || stat.uid !== process.getuid?.() || stat.size > 4096)
|
|
38
|
+
throw new Error('Invalid launcher receipt');
|
|
39
|
+
try {
|
|
40
|
+
return JSON.parse(await handle.readFile('utf8'));
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
throw new Error('Invalid launcher receipt');
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
finally {
|
|
47
|
+
await handle.close();
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
async function parentOf(pid) {
|
|
51
|
+
return exec('/bin/ps', ['-p', String(pid), '-o', 'ppid=']).then(value => Number(value.stdout.trim()) || null).catch(() => null);
|
|
52
|
+
}
|
|
53
|
+
export async function prepareNativeLauncher(directory, record, control, env = process.env, resume = false) {
|
|
54
|
+
if (record.launch.mode !== 'interactive' || record.launch.task !== undefined)
|
|
55
|
+
throw new Error('Interactive panes take no parent input');
|
|
56
|
+
if (createPublicKey({ key: Buffer.from(control.publicKey, 'base64'), format: 'der', type: 'spki' }).asymmetricKeyType !== 'ed25519')
|
|
57
|
+
throw new Error('Invalid desktop public key');
|
|
58
|
+
await ownerDirectory(directory, basename(directory).startsWith('owner-') ? dirname(dirname(directory)) : dirname(directory));
|
|
59
|
+
const pidfile = join(await realpath(directory), `${record.paneId}-${randomUUID()}.pid`);
|
|
60
|
+
const nativeZtc = record.launch.tool === 'ztc';
|
|
61
|
+
const shim = nativeZtc ? pidfile + '.bin' : join(directory, 'bin');
|
|
62
|
+
await ownerDirectory(shim);
|
|
63
|
+
const entry = checkoutEntry();
|
|
64
|
+
const rendererPid = control.rendererPid ?? process.pid;
|
|
65
|
+
const rendererStartMs = await observeProcessStart(rendererPid);
|
|
66
|
+
if (rendererStartMs === null)
|
|
67
|
+
throw new Error('Launcher provenance required');
|
|
68
|
+
const provenance = { nonce: randomBytes(32).toString('hex'), preparedAt: Date.now(), expiresAt: Date.now() + 15000, rendererPid, rendererStartMs, pidfile };
|
|
69
|
+
receipts.set(pidfile, provenance);
|
|
70
|
+
record.provenance = provenance;
|
|
71
|
+
const keys = ['PATH', 'HOME', 'USER', 'LOGNAME', 'SHELL', 'TMPDIR', 'TMP', 'TEMP', 'LANG', 'LC_ALL', 'TZ', 'TERM', 'CI', 'NO_COLOR', 'CODEX_HOME', 'CLAUDE_CONFIG_DIR', 'ZTC_CONFIG_DIR', 'ZTC_PROFILE', 'ZTC_SKILL_PATHS'];
|
|
72
|
+
const inherited = Object.fromEntries(keys.filter(key => env[key] !== undefined).map(key => [key, env[key]]));
|
|
73
|
+
const argv = resume ? buildResumeArgv(record) : buildLaunchArgv(record);
|
|
74
|
+
if (nativeZtc) {
|
|
75
|
+
const handoff = writePaneCredentialHandoff(control.token);
|
|
76
|
+
inherited.TMPDIR = dirname(dirname(handoff));
|
|
77
|
+
try {
|
|
78
|
+
await atomicOwnerFile(pidfile + '.credential', JSON.stringify({ token: control.token, socket: control.socket, publicKey: control.publicKey,
|
|
79
|
+
configRoot: env.ZTC_CONFIG_DIR ?? join(env.HOME ?? homedir(), '.ztc'), handoff }));
|
|
80
|
+
await atomicOwnerFile(join(shim, 'ztc'), `#!/bin/sh\nexec ${[...desktopCredentialShimEntry(), pidfile + '.credential'].map(quote).join(' ')} "$@"\n`, 0o700);
|
|
81
|
+
argv.push(DESKTOP_CREDENTIAL_FILE_FLAG, handoff);
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
removePaneCredentialHandoff(handoff);
|
|
85
|
+
removeDesktopCredentialSource(pidfile);
|
|
86
|
+
throw error;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
else
|
|
90
|
+
await atomicOwnerFile(join(shim, 'ztc'), `#!/bin/sh\nexec ${[entry.command, ...entry.args].map(quote).join(' ')} "$@"\n`, 0o700);
|
|
91
|
+
return { command: env.SHELL ?? '/bin/bash', args: ['-lc', LAUNCHER_SCRIPT, pidfile, provenance.nonce, process.execPath, receiptScript, String(Math.floor((provenance.expiresAt + 2000) / 1000)), record.launch.command,
|
|
92
|
+
...argv],
|
|
93
|
+
// A native ZTC joins the mirror as itself, as any ZTC pane does: the pane transport hands it a credential of its own
|
|
94
|
+
// in a one-time file its command line names, never the owner's (PaneCredentialBroker). Claude Code, Codex and a
|
|
95
|
+
// shell talk to no mirror here, and get none.
|
|
96
|
+
env: { ...inherited, ZTC_DESKTOP_SOCKET: control.socket, ...(!nativeZtc ? { ZTC_DESKTOP_TOKEN: control.token } : { [PANE_CREDENTIAL_ENV]: ZTC_PANE_CREDENTIAL_REQUEST }), ZTC_DESKTOP_PUBLIC_KEY: control.publicKey,
|
|
97
|
+
ZTC_DESKTOP_SHIM: shim, PATH: `${shim}:${env.PATH ?? '/usr/bin:/bin'}` }, pidfile, provenance };
|
|
98
|
+
}
|
|
99
|
+
export function cleanupNativeLauncherCredentials(pidfile) {
|
|
100
|
+
removeDesktopCredentialSource(pidfile);
|
|
101
|
+
}
|
|
102
|
+
export async function observeLauncher(pidfile, owner, previous) {
|
|
103
|
+
const proof = owner.provenance ?? receipts.get(pidfile);
|
|
104
|
+
if (!proof || proof.pidfile !== pidfile)
|
|
105
|
+
throw new Error('Launcher provenance required');
|
|
106
|
+
const first = proof.shellPid === undefined;
|
|
107
|
+
const checkDeadline = () => { if (first && Date.now() > proof.expiresAt)
|
|
108
|
+
throw new Error('Launcher admission expired'); };
|
|
109
|
+
const observe = async (pending) => { try {
|
|
110
|
+
return await pending;
|
|
111
|
+
}
|
|
112
|
+
finally {
|
|
113
|
+
checkDeadline();
|
|
114
|
+
} };
|
|
115
|
+
checkDeadline();
|
|
116
|
+
const value = await observe(receiptFile(pidfile));
|
|
117
|
+
if (value === null)
|
|
118
|
+
return null;
|
|
119
|
+
if (value.nonce !== proof.nonce || !Number.isSafeInteger(value.shellPid) || !Number.isSafeInteger(value.leaderPid)
|
|
120
|
+
|| !Number.isFinite(value.shellStartMs) || !Number.isFinite(value.leaderStartMs))
|
|
121
|
+
throw new Error('Launcher identity lost');
|
|
122
|
+
const shellPid = Number(value.shellPid);
|
|
123
|
+
const shellStartMs = Number(value.shellStartMs);
|
|
124
|
+
const leaderPid = Number(value.leaderPid);
|
|
125
|
+
const leaderStartMs = Number(value.leaderStartMs);
|
|
126
|
+
if (first) {
|
|
127
|
+
if (shellStartMs < proof.preparedAt - 2000 || shellStartMs > proof.expiresAt
|
|
128
|
+
|| leaderStartMs < proof.preparedAt - 2000 || leaderStartMs > proof.expiresAt
|
|
129
|
+
|| await observe(observeProcessStart(shellPid)) !== shellStartMs || await observe(observeProcessStart(leaderPid)) !== leaderStartMs
|
|
130
|
+
|| await observe(parentOf(shellPid)) !== proof.rendererPid || await observe(parentOf(leaderPid)) !== shellPid
|
|
131
|
+
|| await observe(observeProcessStart(proof.rendererPid)) !== proof.rendererStartMs)
|
|
132
|
+
throw new Error('Launcher identity lost');
|
|
133
|
+
}
|
|
134
|
+
if (!first && (shellPid !== proof.shellPid || shellStartMs !== proof.shellStartMs || leaderPid !== proof.leaderPid || leaderStartMs !== proof.leaderStartMs)
|
|
135
|
+
|| previous && previous.shellPid !== shellPid)
|
|
136
|
+
throw new Error('Launcher identity lost');
|
|
137
|
+
const observedStart = await observe(observeProcessStart(leaderPid));
|
|
138
|
+
if (observedStart !== null && observedStart !== leaderStartMs)
|
|
139
|
+
throw new Error('Launcher identity lost');
|
|
140
|
+
const group = previous?.process?.pgid ?? await observe(processGroupOf(leaderPid));
|
|
141
|
+
const identity = previous?.process ?? (group === null ? null : { paneId: owner.paneId, desktopOwnerId: owner.desktopOwnerId, revision: owner.revision, leaderPid, leaderStartMs, pgid: group });
|
|
142
|
+
let exit = null;
|
|
143
|
+
if (first) {
|
|
144
|
+
if (observedStart === null)
|
|
145
|
+
exit = await observe(receiptFile(pidfile + '.exit'));
|
|
146
|
+
const staged = pidfile + '.admit-' + randomUUID();
|
|
147
|
+
try {
|
|
148
|
+
checkDeadline();
|
|
149
|
+
await observe(atomicOwnerFile(staged, proof.nonce));
|
|
150
|
+
let existing;
|
|
151
|
+
try {
|
|
152
|
+
existing = lstatSync(pidfile + '.admit');
|
|
153
|
+
}
|
|
154
|
+
catch (error) {
|
|
155
|
+
if (error.code !== 'ENOENT')
|
|
156
|
+
throw error;
|
|
157
|
+
}
|
|
158
|
+
if (existing?.isSymbolicLink())
|
|
159
|
+
throw Object.assign(new Error('Unsafe owner file'), { code: 'ELOOP' });
|
|
160
|
+
checkDeadline();
|
|
161
|
+
renameSync(staged, pidfile + '.admit');
|
|
162
|
+
const published = lstatSync(pidfile + '.admit');
|
|
163
|
+
if (!published.isFile() || published.nlink !== 1 || published.uid !== process.getuid?.() || (published.mode & 0o777) !== 0o600)
|
|
164
|
+
throw new Error('Unsafe owner file');
|
|
165
|
+
Object.assign(proof, { shellPid, shellStartMs, leaderPid, leaderStartMs });
|
|
166
|
+
}
|
|
167
|
+
finally {
|
|
168
|
+
await unlink(staged).catch((error) => { if (error.code !== 'ENOENT')
|
|
169
|
+
throw error; });
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
else {
|
|
173
|
+
await atomicOwnerFile(pidfile + '.admit', proof.nonce);
|
|
174
|
+
exit = observedStart === null ? await receiptFile(pidfile + '.exit') : null;
|
|
175
|
+
}
|
|
176
|
+
if (exit && (exit.nonce !== proof.nonce || !Number.isInteger(exit.code) || Number(exit.code) < 0 || Number(exit.code) > 255))
|
|
177
|
+
throw new Error('Invalid launcher receipt');
|
|
178
|
+
return { shellPid, shellStartMs, process: identity, exitCode: exit ? Number(exit.code) : null };
|
|
179
|
+
}
|
|
180
|
+
export async function terminateLauncherGroup(pidfile, proof) {
|
|
181
|
+
if (proof.pidfile !== pidfile)
|
|
182
|
+
return false;
|
|
183
|
+
const receipt = await receiptFile(pidfile);
|
|
184
|
+
if (!receipt || receipt.nonce !== proof.nonce)
|
|
185
|
+
return false;
|
|
186
|
+
if (!Number.isSafeInteger(receipt.shellPid) || Number(receipt.shellPid) <= 1 || !Number.isFinite(receipt.shellStartMs))
|
|
187
|
+
return false;
|
|
188
|
+
const pid = Number(receipt.shellPid);
|
|
189
|
+
const start = Number(receipt.shellStartMs);
|
|
190
|
+
if (start < proof.preparedAt - 2000 || start > proof.expiresAt || proof.shellPid !== undefined && proof.shellPid !== pid
|
|
191
|
+
|| proof.shellStartMs !== undefined && proof.shellStartMs !== start || await observeProcessStart(pid) !== start
|
|
192
|
+
|| await parentOf(pid) !== proof.rendererPid || await observeProcessStart(proof.rendererPid) !== proof.rendererStartMs)
|
|
193
|
+
return false;
|
|
194
|
+
const group = await processGroupOf(pid);
|
|
195
|
+
if (group !== pid || group === await processGroupOf(process.pid) || await observeProcessStart(pid) !== start)
|
|
196
|
+
return false;
|
|
197
|
+
try {
|
|
198
|
+
process.kill(-group, 'SIGTERM');
|
|
199
|
+
return true;
|
|
200
|
+
}
|
|
201
|
+
catch {
|
|
202
|
+
return false;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
export async function stopNativePane(record, pidfile, observation, options) {
|
|
206
|
+
if (record.outcome.stopState === 'leader_exited')
|
|
207
|
+
return record.outcome;
|
|
208
|
+
if (!record.process)
|
|
209
|
+
return { ...record.outcome, stopState: 'identity_lost' };
|
|
210
|
+
if (pidfile && (!observation?.process || observation.process.leaderPid !== record.process.leaderPid
|
|
211
|
+
|| observation.process.leaderStartMs !== record.process.leaderStartMs || observation.process.pgid !== record.process.pgid
|
|
212
|
+
|| observation.process.paneId !== record.paneId || record.process.paneId !== record.paneId
|
|
213
|
+
|| observation.process.desktopOwnerId !== record.process.desktopOwnerId))
|
|
214
|
+
return { ...record.outcome, stopState: 'identity_lost' };
|
|
215
|
+
if (pidfile && (!observation || await observeLauncher(pidfile, { ...record.process, provenance: record.provenance }, observation).catch(() => null) === null))
|
|
216
|
+
return { ...record.outcome, stopState: 'identity_lost' };
|
|
217
|
+
if (await validateIdentity(record.process) !== 'valid')
|
|
218
|
+
return { ...record.outcome, stopState: 'identity_lost' };
|
|
219
|
+
const result = await stopSequence(record.process, options);
|
|
220
|
+
if (pidfile && result.stopState === 'leader_exited') {
|
|
221
|
+
const latest = await observeLauncher(pidfile, { ...record.process, provenance: record.provenance }, observation).catch(() => null);
|
|
222
|
+
if (latest?.exitCode !== null && latest?.exitCode !== undefined)
|
|
223
|
+
result.exit = { code: latest.exitCode, signal: null };
|
|
224
|
+
}
|
|
225
|
+
return result;
|
|
226
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { MuxSessionState } from '../../ui/ratatui/protocol.js';
|
|
2
|
+
import { type NativeToolPaneRecord } from './native_tool.js';
|
|
3
|
+
export type SavedNativeRecord = Omit<NativeToolPaneRecord, 'launch'> & {
|
|
4
|
+
launch: Omit<NativeToolPaneRecord['launch'], 'command' | 'args' | 'task'>;
|
|
5
|
+
};
|
|
6
|
+
export type NativeRecords = Record<string, SavedNativeRecord>;
|
|
7
|
+
export declare function savedNativeRecord(record: NativeToolPaneRecord, provenance?: boolean): SavedNativeRecord;
|
|
8
|
+
export type NativeWorkspaceState = MuxSessionState & {
|
|
9
|
+
native_tools?: NativeRecords;
|
|
10
|
+
};
|
|
11
|
+
export declare function parseNativeRecords(value: unknown, paneIds?: ReadonlySet<number>, trustedProvenance?: boolean): Record<string, NativeToolPaneRecord>;
|
|
12
|
+
export declare function savedBrokerUrl(records: NativeRecords): URL | null;
|
|
13
|
+
export declare function nativeWorkspaceState(state: NativeWorkspaceState): NativeWorkspaceState;
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { rebuildNativeLaunch } from './recipes.js';
|
|
2
|
+
import { parseNativeToolPaneRecord } from './native_tool.js';
|
|
3
|
+
export function savedNativeRecord(record, provenance = false) {
|
|
4
|
+
const launch = record.launch;
|
|
5
|
+
return structuredClone({ recordVersion: record.recordVersion, paneId: record.paneId,
|
|
6
|
+
launch: { tool: launch.tool, mode: launch.mode, cwd: launch.cwd, worktree: launch.worktree, profile: launch.profile, model: launch.model,
|
|
7
|
+
effort: launch.effort, sandbox: launch.sandbox, approvalPolicy: launch.approvalPolicy, cliVersion: launch.cliVersion,
|
|
8
|
+
versionRange: launch.versionRange, ...(launch.policy ? { policy: launch.policy } : {}) },
|
|
9
|
+
identity: { canonicalId: record.identity.canonicalId, source: record.identity.source, state: record.identity.state, validatedAt: record.identity.validatedAt },
|
|
10
|
+
process: record.process, outcome: record.outcome, enrollmentId: record.enrollmentId, leaseId: record.leaseId,
|
|
11
|
+
...(provenance && record.provenance ? { provenance: record.provenance } : {}),
|
|
12
|
+
...(provenance && record.launchSeal ? { launchSeal: record.launchSeal } : {}),
|
|
13
|
+
...(provenance && record.leaseAcquiredAt !== undefined ? { leaseAcquiredAt: record.leaseAcquiredAt } : {}),
|
|
14
|
+
...(provenance && record.launchOwnerId ? { launchOwnerId: record.launchOwnerId } : {}),
|
|
15
|
+
...(provenance && record.controlOwnerPid ? { controlOwnerPid: record.controlOwnerPid } : {}),
|
|
16
|
+
...(provenance && record.controlOwnerStartMs !== undefined ? { controlOwnerStartMs: record.controlOwnerStartMs } : {}) });
|
|
17
|
+
}
|
|
18
|
+
export function parseNativeRecords(value, paneIds, trustedProvenance = false) {
|
|
19
|
+
if (value === undefined)
|
|
20
|
+
return {};
|
|
21
|
+
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).length > 256)
|
|
22
|
+
throw new Error('Invalid native pane records');
|
|
23
|
+
const records = {};
|
|
24
|
+
for (const [key, input] of Object.entries(value)) {
|
|
25
|
+
let record;
|
|
26
|
+
try {
|
|
27
|
+
const source = input;
|
|
28
|
+
record = rebuildNativeLaunch(parseNativeToolPaneRecord({ ...source, launch: { ...source.launch, command: 'owner-recipe', args: [] } }));
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
throw new Error('Invalid native pane record');
|
|
32
|
+
}
|
|
33
|
+
if (record.paneId === 0 || String(record.paneId) !== key || paneIds && !paneIds.has(record.paneId))
|
|
34
|
+
throw new Error('Native record names a missing pane');
|
|
35
|
+
delete record.launch.task;
|
|
36
|
+
delete record.identity.locator;
|
|
37
|
+
if (!trustedProvenance) {
|
|
38
|
+
delete record.provenance;
|
|
39
|
+
delete record.launchSeal;
|
|
40
|
+
delete record.leaseAcquiredAt;
|
|
41
|
+
delete record.launchOwnerId;
|
|
42
|
+
delete record.controlOwnerPid;
|
|
43
|
+
delete record.controlOwnerStartMs;
|
|
44
|
+
}
|
|
45
|
+
records[key] = record;
|
|
46
|
+
}
|
|
47
|
+
return records;
|
|
48
|
+
}
|
|
49
|
+
export function savedBrokerUrl(records) {
|
|
50
|
+
const values = new Set(Object.values(records).filter(record => record.launch.tool === 'ztc' && record.launch.mode === 'delegated').map(record => record.launch.policy?.brokerUrl));
|
|
51
|
+
let selected = null;
|
|
52
|
+
for (const value of values) {
|
|
53
|
+
if (!value)
|
|
54
|
+
continue;
|
|
55
|
+
const url = new URL(value);
|
|
56
|
+
if (url.protocol !== 'http:' || url.hostname !== '127.0.0.1' || url.pathname !== '/approvals' || url.username || url.password || url.search || url.hash)
|
|
57
|
+
throw new Error('Saved approval broker is invalid');
|
|
58
|
+
if (values.size === 1)
|
|
59
|
+
selected = url;
|
|
60
|
+
}
|
|
61
|
+
return selected;
|
|
62
|
+
}
|
|
63
|
+
export function nativeWorkspaceState(state) {
|
|
64
|
+
const copy = structuredClone(state);
|
|
65
|
+
if (state.native_tools === undefined)
|
|
66
|
+
return copy;
|
|
67
|
+
copy.native_tools = Object.fromEntries(Object.entries(parseNativeRecords(state.native_tools, new Set(copy.panes.map(pane => pane.id)))).map(([key, record]) => [key, savedNativeRecord(record)]));
|
|
68
|
+
for (const pane of copy.panes) {
|
|
69
|
+
const record = copy.native_tools[String(pane.id)];
|
|
70
|
+
if (!record)
|
|
71
|
+
continue;
|
|
72
|
+
pane.title = `${record.launch.tool} ${record.launch.mode} ${record.identity.state}${record.outcome.containment === 'override' ? ' exclusivity unverified' : ''}`;
|
|
73
|
+
pane.labels = { manual_title: pane.title, project: record.launch.cwd, task: record.launch.mode === 'interactive' ? 'human input only' : 'untrusted feed' };
|
|
74
|
+
delete pane.content;
|
|
75
|
+
delete pane.args;
|
|
76
|
+
delete pane.command;
|
|
77
|
+
delete pane.agent_session;
|
|
78
|
+
pane.pane_type = 'feed';
|
|
79
|
+
}
|
|
80
|
+
return copy;
|
|
81
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { DesktopRouterState } from '../../ui/ratatui/protocol.js';
|
|
2
|
+
import type { DailyDesktopSnapshot } from './desktop_wiring.js';
|
|
3
|
+
export declare function routerChromeState(snapshot: Partial<DailyDesktopSnapshot>): DesktopRouterState;
|
|
4
|
+
export declare function nativeStatusLines(snapshot: Partial<DailyDesktopSnapshot>, selected: number): string[];
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
const count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
|
3
|
+
const child = z.object({ orphaned: z.boolean().optional(), paneId: count, tool: z.enum(['claude_code', 'codex', 'ztc', 'shell']), mode: z.enum(['interactive', 'delegated']),
|
|
4
|
+
taskState: z.enum(['queued', 'running', 'approval_pending', 'exited', 'result_available', 'result_rejected', 'failed']),
|
|
5
|
+
approvalState: z.enum(['none', 'pending', 'denied', 'granted']), identityState: z.enum(['bound', 'unbound', 'mismatched']),
|
|
6
|
+
leaseState: z.enum(['held', 'unverified', 'quarantined', 'none']), containment: z.enum(['unverified', 'escaped', 'override']),
|
|
7
|
+
stopState: z.enum(['running', 'leader_exited', 'identity_lost', 'unknown']), eventCount: count,
|
|
8
|
+
tokens: z.object({ input: count, output: count }).nullable(), freshnessAgeMs: count.nullable() });
|
|
9
|
+
const auth = z.enum(['signed_out', 'expired', 'authentication_rejected', 'unavailable', 'authenticated', 'stale', 'unknown']);
|
|
10
|
+
const funding = z.enum(['ready', 'needs_payment', 'payment_pending', 'payment_failed', 'cap_reached', 'unavailable', 'unknown']);
|
|
11
|
+
export function routerChromeState(snapshot) {
|
|
12
|
+
const authState = auth.safeParse(snapshot.routerAuth?.state);
|
|
13
|
+
const fundingState = funding.safeParse(snapshot.routerFunding?.state);
|
|
14
|
+
const state = authState.success ? authState.data : 'unknown';
|
|
15
|
+
const status = snapshot.routerAuth?.status;
|
|
16
|
+
return { auth: state, ...(state === 'authentication_rejected' && Number.isInteger(status) && status >= 100 && status <= 599 ? { status: status } : {}), funding: fundingState.success ? fundingState.data : 'unknown' };
|
|
17
|
+
}
|
|
18
|
+
export function nativeStatusLines(snapshot, selected) {
|
|
19
|
+
const router = routerChromeState(snapshot);
|
|
20
|
+
return [`Delegated Router auth: ${router.auth}${router.status === undefined ? '' : ' ' + router.status} · Router funding: ${router.funding}`,
|
|
21
|
+
...(snapshot.children ?? []).slice(0, 256).map((value, index) => {
|
|
22
|
+
const parsed = child.safeParse(value);
|
|
23
|
+
if (!parsed.success)
|
|
24
|
+
return `${index === selected ? '>' : ' '} Child unavailable`;
|
|
25
|
+
const item = parsed.data;
|
|
26
|
+
return `${index === selected ? '>' : ' '} pane ${item.paneId} ${item.tool} ${item.mode}${item.orphaned ? ' orphaned' : ''} ${item.taskState} · ${item.identityState} · approval ${item.approvalState} · ${item.containment === 'override' ? 'exclusivity unverified' : item.leaseState} · ${item.stopState} · events ${item.eventCount} · tokens ${item.tokens ? item.tokens.input + '/' + item.tokens.output : 'unknown'} · age ${item.freshnessAgeMs ?? 'unknown'} ms`;
|
|
27
|
+
})];
|
|
28
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export type NativeTool = 'claude_code' | 'codex' | 'ztc' | 'shell';
|
|
3
|
+
export type PaneMode = 'interactive' | 'delegated';
|
|
4
|
+
export interface WorktreeIdentity {
|
|
5
|
+
repositoryRoot: string;
|
|
6
|
+
gitCommonDir: string;
|
|
7
|
+
branch: string | null;
|
|
8
|
+
head: string | null;
|
|
9
|
+
}
|
|
10
|
+
export interface NativeIdentity {
|
|
11
|
+
canonicalId: string | null;
|
|
12
|
+
source: 'launcher_assigned' | 'tool_reported' | 'none';
|
|
13
|
+
state: 'bound' | 'unbound' | 'mismatched';
|
|
14
|
+
validatedAt: number | null;
|
|
15
|
+
locator?: string;
|
|
16
|
+
}
|
|
17
|
+
export interface ProcessIdentity {
|
|
18
|
+
leaderPid: number;
|
|
19
|
+
leaderStartMs: number;
|
|
20
|
+
pgid: number;
|
|
21
|
+
paneId: number;
|
|
22
|
+
desktopOwnerId: string;
|
|
23
|
+
revision: number;
|
|
24
|
+
}
|
|
25
|
+
export type StopState = 'running' | 'leader_exited' | 'identity_lost' | 'unknown';
|
|
26
|
+
export type Containment = 'unverified' | 'escaped' | 'override';
|
|
27
|
+
export interface Outcome {
|
|
28
|
+
exit: {
|
|
29
|
+
code: number | null;
|
|
30
|
+
signal: string | null;
|
|
31
|
+
} | null;
|
|
32
|
+
stopState: StopState;
|
|
33
|
+
survivors: number[];
|
|
34
|
+
containment: Containment;
|
|
35
|
+
}
|
|
36
|
+
export interface EffectivePolicy {
|
|
37
|
+
allowedPaths?: string[];
|
|
38
|
+
deniedPaths?: string[];
|
|
39
|
+
pathPrecedence?: 'deny_first' | 'specific';
|
|
40
|
+
extensions?: 'closed' | 'open';
|
|
41
|
+
autoAccept?: boolean;
|
|
42
|
+
toolAllowlist?: string[];
|
|
43
|
+
authMode?: 'zrouter' | 'direct' | 'auto';
|
|
44
|
+
profileName: string;
|
|
45
|
+
permissionProfile: string;
|
|
46
|
+
capabilities: Record<string, boolean>;
|
|
47
|
+
approvalRequiredCapabilities: string[];
|
|
48
|
+
sandboxBackend: string;
|
|
49
|
+
sandboxEnforcement: 'os' | 'partial' | 'none' | 'unsupported';
|
|
50
|
+
sandboxRequired: boolean;
|
|
51
|
+
brokerUrl: string | null;
|
|
52
|
+
outputSink: string | null;
|
|
53
|
+
schemaId: string | null;
|
|
54
|
+
schemaHash: string | null;
|
|
55
|
+
adapterVersion: string;
|
|
56
|
+
policyHash: string;
|
|
57
|
+
}
|
|
58
|
+
export interface NativeToolLaunch {
|
|
59
|
+
tool: NativeTool;
|
|
60
|
+
mode: PaneMode;
|
|
61
|
+
command: string;
|
|
62
|
+
args: string[];
|
|
63
|
+
cwd: string;
|
|
64
|
+
worktree: WorktreeIdentity;
|
|
65
|
+
profile: string | null;
|
|
66
|
+
model: string | null;
|
|
67
|
+
effort: string | null;
|
|
68
|
+
sandbox: string | null;
|
|
69
|
+
approvalPolicy: string | null;
|
|
70
|
+
cliVersion: string | null;
|
|
71
|
+
versionRange: string;
|
|
72
|
+
task?: string;
|
|
73
|
+
policy?: EffectivePolicy;
|
|
74
|
+
}
|
|
75
|
+
export interface LaunchProvenance {
|
|
76
|
+
nonce: string;
|
|
77
|
+
preparedAt: number;
|
|
78
|
+
expiresAt: number;
|
|
79
|
+
rendererPid: number;
|
|
80
|
+
rendererStartMs: number;
|
|
81
|
+
pidfile: string;
|
|
82
|
+
shellPid?: number;
|
|
83
|
+
shellStartMs?: number;
|
|
84
|
+
leaderPid?: number;
|
|
85
|
+
leaderStartMs?: number;
|
|
86
|
+
}
|
|
87
|
+
export interface NativeToolPaneRecord {
|
|
88
|
+
launchSeal?: string;
|
|
89
|
+
leaseAcquiredAt?: number;
|
|
90
|
+
launchOwnerId?: string;
|
|
91
|
+
controlOwnerPid?: number;
|
|
92
|
+
controlOwnerStartMs?: number;
|
|
93
|
+
provenance?: LaunchProvenance;
|
|
94
|
+
recordVersion: 1;
|
|
95
|
+
paneId: number;
|
|
96
|
+
launch: NativeToolLaunch;
|
|
97
|
+
identity: NativeIdentity;
|
|
98
|
+
process: ProcessIdentity | null;
|
|
99
|
+
outcome: Outcome;
|
|
100
|
+
enrollmentId: string | null;
|
|
101
|
+
leaseId: string | null;
|
|
102
|
+
}
|
|
103
|
+
export declare const nativeIdentitySchema: z.ZodObject<{
|
|
104
|
+
canonicalId: z.ZodNullable<z.ZodUUID>;
|
|
105
|
+
source: z.ZodEnum<{
|
|
106
|
+
launcher_assigned: "launcher_assigned";
|
|
107
|
+
tool_reported: "tool_reported";
|
|
108
|
+
none: "none";
|
|
109
|
+
}>;
|
|
110
|
+
state: z.ZodEnum<{
|
|
111
|
+
bound: "bound";
|
|
112
|
+
unbound: "unbound";
|
|
113
|
+
mismatched: "mismatched";
|
|
114
|
+
}>;
|
|
115
|
+
validatedAt: z.ZodNullable<z.ZodNumber>;
|
|
116
|
+
locator: z.ZodOptional<z.ZodString>;
|
|
117
|
+
}, z.core.$strict>;
|
|
118
|
+
export declare const processIdentitySchema: z.ZodObject<{
|
|
119
|
+
leaderPid: z.ZodNumber;
|
|
120
|
+
leaderStartMs: z.ZodNumber;
|
|
121
|
+
pgid: z.ZodNumber;
|
|
122
|
+
paneId: z.ZodNumber;
|
|
123
|
+
desktopOwnerId: z.ZodString;
|
|
124
|
+
revision: z.ZodNumber;
|
|
125
|
+
}, z.core.$strict>;
|
|
126
|
+
export declare const worktreeIdentitySchema: z.ZodObject<{
|
|
127
|
+
repositoryRoot: z.ZodString;
|
|
128
|
+
gitCommonDir: z.ZodString;
|
|
129
|
+
branch: z.ZodNullable<z.ZodString>;
|
|
130
|
+
head: z.ZodNullable<z.ZodString>;
|
|
131
|
+
}, z.core.$strict>;
|
|
132
|
+
export declare function parseNativeToolPaneRecord(value: unknown): NativeToolPaneRecord;
|
|
133
|
+
export declare function readWorktreeIdentity(cwd: string): Promise<WorktreeIdentity>;
|
|
134
|
+
export declare function policyHash(policy: object): string;
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { realpath } from 'node:fs/promises';
|
|
4
|
+
import { isAbsolute } from 'node:path';
|
|
5
|
+
import { promisify } from 'node:util';
|
|
6
|
+
import { z } from 'zod';
|
|
7
|
+
const count = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
|
|
8
|
+
const pid = count.min(1);
|
|
9
|
+
const text = z.string().max(65536);
|
|
10
|
+
const path = z.string().min(1).max(4096).refine(value => isAbsolute(value) && !/[\x00-\x1f\x7f]/.test(value));
|
|
11
|
+
const hash = z.string().regex(/^[a-f0-9]{64}$/);
|
|
12
|
+
export const nativeIdentitySchema = z.strictObject({
|
|
13
|
+
canonicalId: z.uuid().nullable(), source: z.enum(['launcher_assigned', 'tool_reported', 'none']),
|
|
14
|
+
state: z.enum(['bound', 'unbound', 'mismatched']), validatedAt: count.nullable(), locator: text.optional(),
|
|
15
|
+
}).refine(value => value.state !== 'bound' || value.canonicalId !== null && value.source !== 'none');
|
|
16
|
+
export const processIdentitySchema = z.strictObject({
|
|
17
|
+
leaderPid: pid, leaderStartMs: count, pgid: pid, paneId: count,
|
|
18
|
+
desktopOwnerId: z.string().min(1).max(256), revision: count,
|
|
19
|
+
});
|
|
20
|
+
export const worktreeIdentitySchema = z.strictObject({
|
|
21
|
+
repositoryRoot: path, gitCommonDir: path, branch: text.nullable(), head: z.string().regex(/^[a-f0-9]{40,64}$/).nullable(),
|
|
22
|
+
});
|
|
23
|
+
const policySchema = z.strictObject({
|
|
24
|
+
allowedPaths: z.array(path).optional(), deniedPaths: z.array(path).optional(), pathPrecedence: z.enum(['deny_first', 'specific']).optional(),
|
|
25
|
+
extensions: z.enum(['closed', 'open']).optional(), autoAccept: z.boolean().optional(),
|
|
26
|
+
toolAllowlist: z.array(z.string()).optional(), authMode: z.enum(['zrouter', 'direct', 'auto']).optional(),
|
|
27
|
+
profileName: text, permissionProfile: text, capabilities: z.record(z.string(), z.boolean()),
|
|
28
|
+
approvalRequiredCapabilities: z.array(text), sandboxBackend: text,
|
|
29
|
+
sandboxEnforcement: z.enum(['os', 'partial', 'none', 'unsupported']), sandboxRequired: z.boolean(),
|
|
30
|
+
brokerUrl: z.url().nullable(), outputSink: path.nullable(), schemaId: text.nullable(), schemaHash: hash.nullable(),
|
|
31
|
+
adapterVersion: text, policyHash: z.union([hash, z.literal('')]),
|
|
32
|
+
});
|
|
33
|
+
const paneSchema = z.strictObject({
|
|
34
|
+
launchSeal: hash.optional(), leaseAcquiredAt: count.optional(), launchOwnerId: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/).optional(), controlOwnerPid: pid.optional(), controlOwnerStartMs: count.optional(),
|
|
35
|
+
provenance: z.strictObject({ nonce: hash, preparedAt: count, expiresAt: count, rendererPid: pid, rendererStartMs: count,
|
|
36
|
+
pidfile: path, shellPid: pid.optional(), shellStartMs: count.optional(), leaderPid: pid.optional(), leaderStartMs: count.optional() }).optional(),
|
|
37
|
+
recordVersion: z.literal(1), paneId: count,
|
|
38
|
+
launch: z.strictObject({
|
|
39
|
+
tool: z.enum(['claude_code', 'codex', 'ztc', 'shell']), mode: z.enum(['interactive', 'delegated']),
|
|
40
|
+
command: z.string().min(1).max(4096), args: z.array(text), cwd: path, worktree: worktreeIdentitySchema,
|
|
41
|
+
profile: text.nullable(), model: text.nullable(), effort: text.nullable(), sandbox: text.nullable(),
|
|
42
|
+
approvalPolicy: text.nullable(), cliVersion: text.nullable(), versionRange: text,
|
|
43
|
+
task: text.optional(), policy: policySchema.optional(),
|
|
44
|
+
}),
|
|
45
|
+
identity: nativeIdentitySchema, process: processIdentitySchema.nullable(),
|
|
46
|
+
outcome: z.strictObject({
|
|
47
|
+
exit: z.strictObject({ code: z.number().int().nullable(), signal: z.string().regex(/^SIG[A-Z0-9]+$/).nullable() }).nullable(),
|
|
48
|
+
stopState: z.enum(['running', 'leader_exited', 'identity_lost', 'unknown']), survivors: z.array(pid),
|
|
49
|
+
containment: z.enum(['unverified', 'escaped', 'override']),
|
|
50
|
+
}),
|
|
51
|
+
enrollmentId: z.uuid().nullable(), leaseId: hash.nullable(),
|
|
52
|
+
}).refine(value => value.process === null || value.process.paneId === value.paneId);
|
|
53
|
+
export function parseNativeToolPaneRecord(value) {
|
|
54
|
+
return paneSchema.parse(value);
|
|
55
|
+
}
|
|
56
|
+
const exec = promisify(execFile);
|
|
57
|
+
export async function readWorktreeIdentity(cwd) {
|
|
58
|
+
const env = { ...process.env, GIT_OPTIONAL_LOCKS: '0', GIT_TERMINAL_PROMPT: '0' };
|
|
59
|
+
for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE'])
|
|
60
|
+
delete env[key];
|
|
61
|
+
const git = async (args) => {
|
|
62
|
+
const result = await exec('git', ['-C', cwd, ...args], { env, timeout: 2000, maxBuffer: 1024 * 1024, windowsHide: true });
|
|
63
|
+
return result.stdout.trim();
|
|
64
|
+
};
|
|
65
|
+
const paths = (await git(['rev-parse', '--path-format=absolute', '--show-toplevel', '--git-common-dir'])).split('\n');
|
|
66
|
+
if (paths.length !== 2)
|
|
67
|
+
throw new Error('Invalid worktree identity');
|
|
68
|
+
const [repositoryRoot, gitCommonDir, branch, head] = await Promise.all([
|
|
69
|
+
realpath(paths[0]), realpath(paths[1]),
|
|
70
|
+
git(['symbolic-ref', '--quiet', '--short', 'HEAD']).catch(() => null),
|
|
71
|
+
git(['rev-parse', '--verify', 'HEAD']).catch(() => null),
|
|
72
|
+
]);
|
|
73
|
+
return worktreeIdentitySchema.parse({ repositoryRoot, gitCommonDir, branch, head });
|
|
74
|
+
}
|
|
75
|
+
function canonical(value) {
|
|
76
|
+
if (value === null || typeof value === 'boolean' || typeof value === 'string')
|
|
77
|
+
return JSON.stringify(value);
|
|
78
|
+
if (typeof value === 'number' && Number.isFinite(value))
|
|
79
|
+
return JSON.stringify(value);
|
|
80
|
+
if (Array.isArray(value))
|
|
81
|
+
return `[${value.map(canonical).join(',')}]`;
|
|
82
|
+
if (typeof value === 'object' && value !== null) {
|
|
83
|
+
const fields = value;
|
|
84
|
+
return `{${Object.keys(fields).sort().map(key => `${JSON.stringify(key)}:${canonical(fields[key])}`).join(',')}}`;
|
|
85
|
+
}
|
|
86
|
+
throw new Error('Policy must contain JSON values');
|
|
87
|
+
}
|
|
88
|
+
export function policyHash(policy) {
|
|
89
|
+
const fields = Object.fromEntries(Object.entries(policy).filter(([key]) => key !== 'policyHash'));
|
|
90
|
+
return createHash('sha256').update(canonical(fields)).digest('hex');
|
|
91
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export declare function ownerDirectory(path: string, boundary?: string): Promise<void>;
|
|
2
|
+
export declare function atomicOwnerFile(path: string, data: string | Uint8Array, mode?: number): Promise<void>;
|
|
3
|
+
export declare function atomicOwnerFileSync(path: string, data: string): void;
|