@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,25 @@
1
+ import { z } from 'zod';
2
+ const count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
3
+ const path = z.string().max(4096).refine(value => (value === '' || value.startsWith('/')) && !/[\x00-\x1f\x7f]/.test(value));
4
+ export const controlIdentitySchema = z.strictObject({ paneId: count, sessionId: z.uuid().nullable(), ownerId: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/), revision: count });
5
+ const status = z.enum(['pending', 'ready', 'unavailable']);
6
+ const exit = z.strictObject({ code: z.number().int().nullable(), signal: z.string().regex(/^SIG[A-Z0-9]+$/).nullable() }).nullable();
7
+ const summary = z.strictObject({ orphaned: z.boolean(), paneId: count, enrollmentId: z.uuid(), tool: z.enum(['claude_code', 'codex', 'ztc', 'shell']), mode: z.enum(['interactive', 'delegated']),
8
+ identityState: z.enum(['bound', 'unbound', 'mismatched']), canonicalId: z.uuid().nullable(), processState: z.enum(['running', 'exited', 'unknown']),
9
+ stopState: z.enum(['running', 'leader_exited', 'identity_lost', 'unknown']), leaseState: z.enum(['held', 'unverified', 'quarantined', 'none']),
10
+ containment: z.enum(['unverified', 'escaped', 'override']), approvalState: z.enum(['none', 'pending', 'denied', 'granted']),
11
+ taskState: z.enum(['queued', 'running', 'approval_pending', 'exited', 'result_available', 'result_rejected', 'failed']),
12
+ rejectReason: z.enum(['empty_sink', 'malformed_json', 'unknown_schema', 'schema_hash_mismatch', 'extra_key', 'missing_key', 'unsupported_field_type', 'enum_member_invalid', 'number_out_of_range', 'nonzero_exit', 'source_tree_write']).nullable(),
13
+ errorClass: z.enum(['none', 'launch_refused', 'exited_nonzero', 'adapter', 'timeout', 'identity_mismatch']), worktree: path, resultPath: path.nullable(),
14
+ startedAt: count, lastActivityAt: count.nullable(), freshnessAgeMs: count.nullable(), eventCount: count,
15
+ tokens: z.strictObject({ input: count, output: count }).nullable(), exitStatus: exit, provenance: z.enum(['desktop', 'tool_event', 'none']) });
16
+ const result = z.strictObject({ status: z.enum(['ok', 'error']), line_count: count.max(1000000), match_count: count.max(1000000), checksum_hi: count.max(65535), checksum_lo: count.max(65535) }).nullable();
17
+ const routerAuth = z.strictObject({ profile: z.literal('desktop-delegated'), state: z.enum(['signed_out', 'expired', 'authentication_rejected', 'unavailable', 'authenticated', 'stale', 'unknown']), status: z.number().int().nullable(), checkedAt: count.nullable(), ageMs: count.nullable(), expiresAt: z.iso.datetime().nullable() });
18
+ const child = z.strictObject({ routerAuth, status_pane: status, summary, identity: controlIdentitySchema, orphaned: z.boolean(), result }).refine(value => value.summary.paneId === value.identity.paneId && value.summary.canonicalId === value.identity.sessionId && value.summary.orphaned === value.orphaned);
19
+ const failure = z.strictObject({ ok: z.literal(false), error: z.strictObject({ class: z.enum(['unauthorized', 'stale', 'forbidden_interactive', 'unknown_schema', 'lease_refused', 'launch_refused', 'not_found', 'invalid']) }) });
20
+ export function parseControlResponse(op, value) {
21
+ const payload = op === 'list' ? z.strictObject({ children: z.array(child).max(256), identity: controlIdentitySchema, status_pane: status, routerAuth }).refine(value => value.children.every(child => child.identity.ownerId === value.identity.ownerId))
22
+ : op === 'close' ? z.strictObject({ paneId: count }) : child;
23
+ const parsed = z.union([failure, z.strictObject({ ok: z.literal(true), result: payload })]).safeParse(value);
24
+ return parsed.success ? parsed.data : { ok: false, error: { class: 'unknown_schema' } };
25
+ }
@@ -0,0 +1,44 @@
1
+ import { DailyStore, type ChildResources } from './daily_store.js';
2
+ import { type ControlErrorClass } from './control_protocol.js';
3
+ import type { NativeToolPaneRecord, Outcome } from './native_tool.js';
4
+ declare const operations: readonly ["open", "list", "summary", "stop", "resume", "close"];
5
+ export interface OpenChildRequest {
6
+ parentPaneId?: number;
7
+ tool: 'codex' | 'ztc';
8
+ mode: 'delegated';
9
+ worktree: string;
10
+ task: string;
11
+ schemaId: 'fixture-count-v1';
12
+ }
13
+ export interface OpenedChild extends ChildResources {
14
+ record: NativeToolPaneRecord;
15
+ start?: () => void;
16
+ cancel?: () => Promise<void>;
17
+ }
18
+ export interface ControlLog {
19
+ op: typeof operations[number] | null;
20
+ paneId: number | null;
21
+ receivedAt: number;
22
+ completedAt: number;
23
+ errorClass: ControlErrorClass | null;
24
+ }
25
+ export interface ControlServerOptions {
26
+ store: DailyStore;
27
+ managed?: boolean;
28
+ configRoot?: string;
29
+ runtimeRoot?: string;
30
+ open: (request: OpenChildRequest) => Promise<OpenedChild>;
31
+ stop?: (record: NativeToolPaneRecord) => Promise<Outcome>;
32
+ resume?: (record: NativeToolPaneRecord, prompt?: string) => Promise<NativeToolPaneRecord>;
33
+ close?: (paneId: number) => Promise<void>;
34
+ }
35
+ export interface ControlServer {
36
+ readonly publicKey: string;
37
+ socketPath: string;
38
+ discoveryPath: string;
39
+ readonly log: readonly ControlLog[];
40
+ close(): Promise<void>;
41
+ }
42
+ export declare function readTaskFile(path: string): Promise<string>;
43
+ export declare function createControlServer(options: ControlServerOptions): Promise<ControlServer>;
44
+ export {};
@@ -0,0 +1,286 @@
1
+ import { atomicOwnerFileSync } from './owner_files.js';
2
+ import { lstatSync } from 'node:fs';
3
+ import { createServer } from 'node:net';
4
+ import { constants } from 'node:fs';
5
+ import { chmod, lstat, mkdir, open, unlink, realpath } from 'node:fs/promises';
6
+ import { createHash, generateKeyPairSync, sign } from 'node:crypto';
7
+ import { helloRequestSchema, helloMessage } from './control_hello.js';
8
+ import { homedir } from 'node:os';
9
+ import { isAbsolute, join } from 'node:path';
10
+ import { StringDecoder } from 'node:string_decoder';
11
+ import { z } from 'zod';
12
+ import { DailyError } from './control_protocol.js';
13
+ import { validateRequest } from './enrollment.js';
14
+ import { schemaRegistry } from './schema_registry.js';
15
+ import { observeProcessStart, stopSequence } from './process_identity.js';
16
+ const operations = ['open', 'list', 'summary', 'stop', 'resume', 'close'];
17
+ const requestSchema = z.strictObject({ token: z.string().max(256), op: z.enum(operations), paneId: z.number().int().nonnegative().optional(),
18
+ sessionId: z.string().max(256).nullable(), ownerId: z.string().max(64), revision: z.number().int().nonnegative(),
19
+ args: z.record(z.string(), z.unknown()) });
20
+ const openSchema = z.strictObject({ tool: z.enum(['codex', 'ztc']), mode: z.enum(['delegated', 'interactive']), worktree: z.string().max(4096),
21
+ taskFile: z.string().min(1).max(4096), schemaId: z.string().max(128) });
22
+ const resumeSchema = z.strictObject({ taskFile: z.string().min(1).max(4096).optional() });
23
+ export async function readTaskFile(path) {
24
+ if (!isAbsolute(path) || /[\x00-\x1f\x7f]/.test(path))
25
+ throw new DailyError('invalid');
26
+ const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
27
+ try {
28
+ const stat = await handle.stat();
29
+ if (!stat.isFile() || stat.size > 65536)
30
+ throw new DailyError('invalid');
31
+ const buffer = Buffer.alloc(65537);
32
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
33
+ const text = buffer.subarray(0, bytesRead).toString('utf8');
34
+ if (bytesRead > 65536 || !text.trim() || text.includes('\0'))
35
+ throw new DailyError('invalid');
36
+ return text;
37
+ }
38
+ finally {
39
+ await handle.close();
40
+ }
41
+ }
42
+ async function controlSocket(directory, ownerId, root) {
43
+ const fallback = () => {
44
+ const path = join(directory, `control-${ownerId}.sock`);
45
+ if (Buffer.byteLength(path) > 103)
46
+ throw new DailyError('launch_refused');
47
+ return path;
48
+ };
49
+ const uid = process.getuid?.();
50
+ if (uid === undefined)
51
+ return fallback();
52
+ let resolved;
53
+ try {
54
+ resolved = await realpath(root);
55
+ const info = await lstat(resolved);
56
+ if (!info.isDirectory() || info.isSymbolicLink() || ![0, uid].includes(info.uid)
57
+ || (info.mode & 0o022) !== 0 && (info.mode & 0o1000) === 0)
58
+ return fallback();
59
+ }
60
+ catch {
61
+ return fallback();
62
+ }
63
+ const runtime = join(resolved, `ztc-dd-${uid}`);
64
+ try {
65
+ await mkdir(runtime, { mode: 0o700 });
66
+ }
67
+ catch (error) {
68
+ if (error.code !== 'EEXIST')
69
+ return fallback();
70
+ }
71
+ const info = await lstat(runtime);
72
+ if (info.uid !== uid)
73
+ return fallback();
74
+ if (!info.isDirectory() || info.isSymbolicLink() || info.uid !== uid || (info.mode & 0o7777) !== 0o700)
75
+ throw new DailyError('launch_refused');
76
+ const path = join(runtime, createHash('sha256').update(ownerId).digest('hex').slice(0, 16) + '.sock');
77
+ return Buffer.byteLength(path) <= 103 ? path : fallback();
78
+ }
79
+ export async function createControlServer(options) {
80
+ const { store } = options;
81
+ const keys = generateKeyPairSync('ed25519');
82
+ const publicKey = keys.publicKey.export({ format: 'der', type: 'spki' }).toString('base64');
83
+ const directory = join(options.configRoot ?? process.env.ZTC_CONFIG_DIR ?? join(homedir(), '.ztc'), 'desktop');
84
+ await mkdir(directory, { recursive: true, mode: 0o700 });
85
+ const metadata = await lstat(directory);
86
+ if (!metadata.isDirectory() || metadata.isSymbolicLink() || metadata.uid !== process.getuid?.())
87
+ throw new DailyError('launch_refused');
88
+ await chmod(directory, 0o700);
89
+ const socketPath = await controlSocket(directory, store.ownerId, options.runtimeRoot ?? '/tmp');
90
+ const discoveryPath = join(directory, `control-${store.ownerId}.json`);
91
+ const log = [];
92
+ const clients = new Set();
93
+ const busy = new Set();
94
+ const handle = async (input) => {
95
+ const parsed = requestSchema.safeParse(input);
96
+ if (!parsed.success)
97
+ throw new DailyError('invalid');
98
+ const request = parsed.data;
99
+ if (!['list', 'open'].includes(request.op) && request.paneId === undefined)
100
+ throw new DailyError('invalid');
101
+ const authority = store.authorityFor(request.token, request.paneId);
102
+ const identity = authority.identity;
103
+ const normalized = { token: request.token, op: request.op, paneId: request.paneId ?? identity.paneId,
104
+ sessionId: request.sessionId, ownerId: request.ownerId,
105
+ revision: request.revision, args: {} };
106
+ let task;
107
+ let opening;
108
+ if (request.op === 'open') {
109
+ const args = openSchema.safeParse(request.args);
110
+ if (!args.success)
111
+ throw new DailyError('invalid');
112
+ opening = args.data;
113
+ if (opening.mode === 'interactive')
114
+ throw new DailyError('forbidden_interactive');
115
+ if (!Object.hasOwn(schemaRegistry, opening.schemaId))
116
+ throw new DailyError('unknown_schema');
117
+ if (opening.worktree !== 'new' && !isAbsolute(opening.worktree))
118
+ throw new DailyError('invalid');
119
+ normalized.args = { tool: opening.tool, mode: opening.mode, worktree: opening.worktree, task: '', schemaId: opening.schemaId };
120
+ }
121
+ else if (request.op === 'resume') {
122
+ const args = resumeSchema.safeParse(request.args);
123
+ if (!args.success)
124
+ throw new DailyError('invalid');
125
+ if (args.data.taskFile !== undefined) {
126
+ if (authority.record.launch.mode === 'interactive')
127
+ throw new DailyError('forbidden_interactive');
128
+ normalized.args = { prompt: '' };
129
+ }
130
+ }
131
+ else if (Object.keys(request.args).length > 0)
132
+ throw new DailyError('invalid');
133
+ const verdict = validateRequest(normalized, authority);
134
+ if (verdict !== 'ok')
135
+ throw new DailyError(verdict);
136
+ if (request.op === 'open')
137
+ task = await readTaskFile(opening.taskFile);
138
+ if (request.op === 'resume' && request.args.taskFile !== undefined)
139
+ task = await readTaskFile(request.args.taskFile);
140
+ const current = store.authorityFor(request.token, normalized.paneId);
141
+ const rechecked = validateRequest(normalized, current);
142
+ if (rechecked !== 'ok')
143
+ throw new DailyError(rechecked);
144
+ if (request.op === 'list')
145
+ return { ok: true, result: { children: store.listChildrenFor(request.token), identity: current.identity, status_pane: store.statusPane, routerAuth: store.routerAuth } };
146
+ if (request.op === 'summary')
147
+ return { ok: true, result: store.summaryFor(request.token, normalized.paneId) };
148
+ if (busy.has(normalized.paneId))
149
+ throw new DailyError('stale');
150
+ busy.add(normalized.paneId);
151
+ try {
152
+ if (request.op === 'open') {
153
+ const opened = await options.open({ parentPaneId: authority.grant.parentPaneId, tool: opening.tool, mode: 'delegated', worktree: opening.worktree, task: task, schemaId: 'fixture-count-v1' });
154
+ const snapshot = await store.addOpenedChild(authority.grant.grantId, opened.record, opened, authority.grant);
155
+ if (snapshot.orphaned) {
156
+ if (opened.cancel) {
157
+ await opened.cancel();
158
+ store.removeChild(opened.record.paneId);
159
+ }
160
+ throw new DailyError('unauthorized');
161
+ }
162
+ opened.start?.();
163
+ return { ok: true, result: snapshot };
164
+ }
165
+ const record = store.getRecord(normalized.paneId);
166
+ if (request.op === 'resume') {
167
+ if (!options.resume || record.identity.state !== 'bound' || record.identity.canonicalId === null)
168
+ throw new DailyError('launch_refused');
169
+ if (store.leaseFor(record.paneId)?.lease.usedWritable)
170
+ throw new DailyError('lease_refused');
171
+ const resumed = await options.resume(record, task);
172
+ if (!options.managed)
173
+ store.updateRecord(resumed, current.identity.revision);
174
+ return { ok: true, result: store.summaryFor(request.token, record.paneId) };
175
+ }
176
+ const stop = async () => options.stop ? options.stop(record) : record.process === null
177
+ ? { ...record.outcome, stopState: 'unknown' } : stopSequence(record.process, { confirmKill: async () => false });
178
+ if (request.op === 'stop') {
179
+ record.outcome = await stop();
180
+ if (!options.managed)
181
+ store.updateRecord(record, current.identity.revision);
182
+ return { ok: true, result: store.summaryFor(request.token, record.paneId) };
183
+ }
184
+ if (record.process !== null && record.outcome.stopState !== 'leader_exited') {
185
+ record.outcome = await stop();
186
+ if (!options.managed)
187
+ store.updateRecord(record, current.identity.revision);
188
+ if (record.outcome.stopState !== 'leader_exited')
189
+ throw new DailyError('launch_refused');
190
+ }
191
+ await options.close?.(record.paneId);
192
+ store.removeChild(record.paneId);
193
+ return { ok: true, result: { paneId: record.paneId } };
194
+ }
195
+ finally {
196
+ busy.delete(normalized.paneId);
197
+ }
198
+ };
199
+ const server = createServer(client => {
200
+ clients.add(client);
201
+ client.setTimeout(30000, () => client.destroy());
202
+ client.on('error', () => { });
203
+ const decoder = new StringDecoder('utf8');
204
+ let buffer = '';
205
+ let queue = Promise.resolve();
206
+ let welcomed = false;
207
+ client.on('data', bytes => {
208
+ buffer += decoder.write(bytes);
209
+ if (Buffer.byteLength(buffer) > 131072) {
210
+ client.end(JSON.stringify({ ok: false, error: { class: 'invalid' } }) + '\n');
211
+ return;
212
+ }
213
+ const lines = buffer.split('\n');
214
+ buffer = lines.pop();
215
+ for (const line of lines) {
216
+ queue = queue.then(async () => {
217
+ const receivedAt = Date.now();
218
+ let response;
219
+ let input;
220
+ try {
221
+ if (Buffer.byteLength(line) > 65536)
222
+ throw new DailyError('invalid');
223
+ input = JSON.parse(line);
224
+ if (!welcomed) {
225
+ const hello = helloRequestSchema.safeParse(input);
226
+ if (!hello.success)
227
+ throw new DailyError('invalid');
228
+ welcomed = true;
229
+ client.write(JSON.stringify({ op: 'hello', signature: sign(null, helloMessage(hello.data.challenge, socketPath, store.ownerId), keys.privateKey).toString('base64') }) + '\n');
230
+ return;
231
+ }
232
+ response = await handle(input);
233
+ }
234
+ catch (error) {
235
+ response = { ok: false, error: { class: error instanceof DailyError ? error.class : error instanceof SyntaxError ? 'invalid' : error.code === 'ENOENT' ? 'not_found' : 'launch_refused' } };
236
+ }
237
+ const parsed = requestSchema.safeParse(input);
238
+ log.push({ op: parsed.success ? parsed.data.op : null, paneId: parsed.success ? parsed.data.paneId ?? null : null,
239
+ receivedAt, completedAt: Date.now(), errorClass: response.ok ? null : response.error.class });
240
+ if (log.length > 1000)
241
+ log.shift();
242
+ if (!client.destroyed)
243
+ client.write(JSON.stringify(response) + '\n');
244
+ }).catch(() => { client.destroy(); });
245
+ }
246
+ });
247
+ client.on('close', () => clients.delete(client));
248
+ });
249
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(socketPath, () => { server.off('error', reject); resolve(); }); });
250
+ server.on('error', () => { for (const client of clients)
251
+ client.destroy(); });
252
+ let discoveryWritten = false;
253
+ let owned;
254
+ const startedAt = await observeProcessStart(process.pid);
255
+ const publishDiscovery = () => {
256
+ atomicOwnerFileSync(discoveryPath, JSON.stringify({ socket: socketPath, ownerId: store.ownerId, pid: process.pid,
257
+ startedAt, uid: process.getuid?.(), publicKey, identities: store.discoveryIdentities() }));
258
+ owned = lstatSync(discoveryPath);
259
+ discoveryWritten = true;
260
+ };
261
+ try {
262
+ await chmod(socketPath, 0o600);
263
+ publishDiscovery();
264
+ }
265
+ catch (error) {
266
+ await new Promise(resolve => server.close(() => resolve()));
267
+ throw error;
268
+ }
269
+ const unsubscribe = store.onChange(() => { try {
270
+ publishDiscovery();
271
+ }
272
+ catch { } });
273
+ return { publicKey, socketPath, discoveryPath, get log() { return log.map(entry => ({ ...entry })); },
274
+ close: async () => {
275
+ unsubscribe();
276
+ for (const client of clients)
277
+ client.destroy();
278
+ await new Promise(resolve => server.close(() => resolve()));
279
+ if (discoveryWritten) {
280
+ const current = await lstat(discoveryPath).catch(() => null);
281
+ if (owned && current?.dev === owned.dev && current.ino === owned.ino)
282
+ await unlink(discoveryPath);
283
+ discoveryWritten = false;
284
+ }
285
+ } };
286
+ }
@@ -0,0 +1,71 @@
1
+ import { type RouterAuthSnapshot } from './router_state.js';
2
+ import { type NativeRecords } from './native_records.js';
3
+ import { validateRequest, type Enrollment, type ParentGrant, type RequestAuthority } from './enrollment.js';
4
+ import { type NativeToolPaneRecord } from './native_tool.js';
5
+ import { type SummaryTask } from './summary.js';
6
+ import { type Projection } from './schema_registry.js';
7
+ import type { LeaseView } from './lease.js';
8
+ import type { ApprovalBroker } from './broker.js';
9
+ import { type ChildSnapshot, type ControlIdentity, type StatusPaneState } from './control_protocol.js';
10
+ export interface ChildResources {
11
+ lease?: LeaseView;
12
+ broker?: ApprovalBroker;
13
+ }
14
+ export interface DailyObservation {
15
+ state: SummaryTask['state'] | 'approval_denied';
16
+ approvalState: SummaryTask['approvalState'];
17
+ errorClass: SummaryTask['errorClass'];
18
+ eventCount: number;
19
+ tokens: SummaryTask['tokens'];
20
+ projection: Projection;
21
+ }
22
+ export declare class DailyStore {
23
+ readonly ownerId: string;
24
+ private readonly now;
25
+ private readonly observers;
26
+ onChange(observer: () => void): () => void;
27
+ private changed;
28
+ discoveryIdentities(): Record<string, ControlIdentity>;
29
+ private router;
30
+ get routerAuth(): import("./router_state.js").DelegatedAuthView;
31
+ setRouterAuth(auth: RouterAuthSnapshot): void;
32
+ private paneStatus;
33
+ get statusPane(): StatusPaneState;
34
+ setStatusPane(state: StatusPaneState): void;
35
+ private readonly entries;
36
+ private readonly grants;
37
+ constructor(ownerId: string, now?: () => number);
38
+ private entry;
39
+ private grant;
40
+ private canSee;
41
+ private makeEntry;
42
+ registerParent(record: NativeToolPaneRecord, token?: string): Promise<ParentGrant>;
43
+ admitParent(paneId: number): void;
44
+ addChild(token: string, record: NativeToolPaneRecord, resources?: ChildResources): Promise<ChildSnapshot>;
45
+ addOpenedChild(grantId: string, record: NativeToolPaneRecord, resources?: ChildResources, revokedGrant?: ParentGrant): Promise<ChildSnapshot>;
46
+ hasRecord(paneId: number): boolean;
47
+ identityFor(paneId: number): ControlIdentity;
48
+ authorityFor(token: string, paneId?: number): RequestAuthority & {
49
+ identity: ControlIdentity;
50
+ };
51
+ validate(input: Parameters<typeof validateRequest>[0], token: string, paneId?: number): ReturnType<typeof validateRequest>;
52
+ listChildrenFor(token: string): ChildSnapshot[];
53
+ summaryFor(token: string, paneId: number): ChildSnapshot;
54
+ snapshotForOwner(paneId: number): ChildSnapshot;
55
+ getRecord(paneId: number): NativeToolPaneRecord;
56
+ enrollmentFor(paneId: number): Enrollment;
57
+ leaseFor(paneId: number): LeaseView | null;
58
+ updateRecord(record: NativeToolPaneRecord, expectedRevision?: number): ControlIdentity;
59
+ setObservation(record: NativeToolPaneRecord, observation: DailyObservation): void;
60
+ revokeParent(paneId: number): void;
61
+ adoptChild(paneId: number, parentToken: string): Enrollment;
62
+ removeChild(paneId: number): void;
63
+ parentPaneIdsForOwner(): number[];
64
+ parentTokenForOwner(paneId: number): string;
65
+ childrenForOwner(): ChildSnapshot[];
66
+ setLease(paneId: number, lease: LeaseView | null): void;
67
+ observeLease(paneId: number, lease: LeaseView): void;
68
+ clearChildren(): void;
69
+ exportRecords(): NativeRecords;
70
+ importRecords(input: unknown, keepRoot?: boolean): Promise<void>;
71
+ }