@xenosystem/agent-sdk 0.8.12

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 (175) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +511 -0
  3. package/dist/agents/index.cjs +17 -0
  4. package/dist/agents/index.d.cts +244 -0
  5. package/dist/agents/index.d.ts +244 -0
  6. package/dist/agents/index.js +17 -0
  7. package/dist/agents/metafile-cjs.json +1 -0
  8. package/dist/agents/metafile-esm.json +1 -0
  9. package/dist/artifacts/browser.cjs +1 -0
  10. package/dist/artifacts/browser.d.cts +8 -0
  11. package/dist/artifacts/browser.d.ts +8 -0
  12. package/dist/artifacts/browser.js +1 -0
  13. package/dist/artifacts/diff-artifact-C2tQZWcs.d.cts +354 -0
  14. package/dist/artifacts/diff-artifact-C2tQZWcs.d.ts +354 -0
  15. package/dist/artifacts/index.cjs +10 -0
  16. package/dist/artifacts/index.d.cts +588 -0
  17. package/dist/artifacts/index.d.ts +588 -0
  18. package/dist/artifacts/index.js +10 -0
  19. package/dist/artifacts/metafile-cjs.json +1 -0
  20. package/dist/artifacts/metafile-esm.json +1 -0
  21. package/dist/automation/index.cjs +438 -0
  22. package/dist/automation/index.d.cts +878 -0
  23. package/dist/automation/index.d.ts +878 -0
  24. package/dist/automation/index.js +438 -0
  25. package/dist/automation/metafile-cjs.json +1 -0
  26. package/dist/automation/metafile-esm.json +1 -0
  27. package/dist/control-plane/index.cjs +7 -0
  28. package/dist/control-plane/index.d.cts +403 -0
  29. package/dist/control-plane/index.d.ts +403 -0
  30. package/dist/control-plane/index.js +7 -0
  31. package/dist/control-plane/metafile-cjs.json +1 -0
  32. package/dist/control-plane/metafile-esm.json +1 -0
  33. package/dist/control-room/index.cjs +1 -0
  34. package/dist/control-room/index.d.cts +216 -0
  35. package/dist/control-room/index.d.ts +216 -0
  36. package/dist/control-room/index.js +1 -0
  37. package/dist/control-room/metafile-cjs.json +1 -0
  38. package/dist/control-room/metafile-esm.json +1 -0
  39. package/dist/electron/index.cjs +1476 -0
  40. package/dist/electron/index.d.cts +1583 -0
  41. package/dist/electron/index.d.ts +1583 -0
  42. package/dist/electron/index.js +1476 -0
  43. package/dist/electron/metafile-cjs.json +1 -0
  44. package/dist/electron/metafile-esm.json +1 -0
  45. package/dist/governance/index.cjs +33 -0
  46. package/dist/governance/index.d.cts +397 -0
  47. package/dist/governance/index.d.ts +397 -0
  48. package/dist/governance/index.js +33 -0
  49. package/dist/governance/metafile-cjs.json +1 -0
  50. package/dist/governance/metafile-esm.json +1 -0
  51. package/dist/hooks/index.cjs +9 -0
  52. package/dist/hooks/index.d.cts +198 -0
  53. package/dist/hooks/index.d.ts +198 -0
  54. package/dist/hooks/index.js +9 -0
  55. package/dist/hooks/metafile-cjs.json +1 -0
  56. package/dist/hooks/metafile-esm.json +1 -0
  57. package/dist/hosted/index.cjs +1 -0
  58. package/dist/hosted/index.d.cts +490 -0
  59. package/dist/hosted/index.d.ts +490 -0
  60. package/dist/hosted/index.js +1 -0
  61. package/dist/hosted/metafile-cjs.json +1 -0
  62. package/dist/hosted/metafile-esm.json +1 -0
  63. package/dist/index.cjs +2161 -0
  64. package/dist/index.d.cts +12259 -0
  65. package/dist/index.d.ts +12259 -0
  66. package/dist/index.js +2161 -0
  67. package/dist/intelligence/index.cjs +10 -0
  68. package/dist/intelligence/index.d.cts +220 -0
  69. package/dist/intelligence/index.d.ts +220 -0
  70. package/dist/intelligence/index.js +10 -0
  71. package/dist/intelligence/metafile-cjs.json +1 -0
  72. package/dist/intelligence/metafile-esm.json +1 -0
  73. package/dist/mcp/index.cjs +28 -0
  74. package/dist/mcp/index.d.cts +960 -0
  75. package/dist/mcp/index.d.ts +960 -0
  76. package/dist/mcp/index.js +28 -0
  77. package/dist/mcp/metafile-cjs.json +1 -0
  78. package/dist/mcp/metafile-esm.json +1 -0
  79. package/dist/metafile-cjs.json +1 -0
  80. package/dist/metafile-esm.json +1 -0
  81. package/dist/oracle/index.cjs +1 -0
  82. package/dist/oracle/index.d.cts +310 -0
  83. package/dist/oracle/index.d.ts +310 -0
  84. package/dist/oracle/index.js +1 -0
  85. package/dist/oracle/metafile-cjs.json +1 -0
  86. package/dist/oracle/metafile-esm.json +1 -0
  87. package/dist/providers/index.cjs +11 -0
  88. package/dist/providers/index.d.cts +462 -0
  89. package/dist/providers/index.d.ts +462 -0
  90. package/dist/providers/index.js +11 -0
  91. package/dist/providers/metafile-cjs.json +1 -0
  92. package/dist/providers/metafile-esm.json +1 -0
  93. package/dist/recipes/index.cjs +2 -0
  94. package/dist/recipes/index.d.cts +86 -0
  95. package/dist/recipes/index.d.ts +86 -0
  96. package/dist/recipes/index.js +2 -0
  97. package/dist/recipes/metafile-cjs.json +1 -0
  98. package/dist/recipes/metafile-esm.json +1 -0
  99. package/dist/research/index.cjs +3 -0
  100. package/dist/research/index.d.cts +285 -0
  101. package/dist/research/index.d.ts +285 -0
  102. package/dist/research/index.js +3 -0
  103. package/dist/research/metafile-cjs.json +1 -0
  104. package/dist/research/metafile-esm.json +1 -0
  105. package/dist/session/index.cjs +56 -0
  106. package/dist/session/index.d.cts +523 -0
  107. package/dist/session/index.d.ts +523 -0
  108. package/dist/session/index.js +56 -0
  109. package/dist/session/metafile-cjs.json +1 -0
  110. package/dist/session/metafile-esm.json +1 -0
  111. package/dist/sharing/index.cjs +4 -0
  112. package/dist/sharing/index.d.cts +272 -0
  113. package/dist/sharing/index.d.ts +272 -0
  114. package/dist/sharing/index.js +4 -0
  115. package/dist/sharing/metafile-cjs.json +1 -0
  116. package/dist/sharing/metafile-esm.json +1 -0
  117. package/dist/skills/index.cjs +6 -0
  118. package/dist/skills/index.d.cts +277 -0
  119. package/dist/skills/index.d.ts +277 -0
  120. package/dist/skills/index.js +6 -0
  121. package/dist/skills/metafile-cjs.json +1 -0
  122. package/dist/skills/metafile-esm.json +1 -0
  123. package/dist/soul/index.cjs +32 -0
  124. package/dist/soul/index.d.cts +138 -0
  125. package/dist/soul/index.d.ts +138 -0
  126. package/dist/soul/index.js +32 -0
  127. package/dist/soul/metafile-cjs.json +1 -0
  128. package/dist/soul/metafile-esm.json +1 -0
  129. package/dist/terminal/index.cjs +4 -0
  130. package/dist/terminal/index.d.cts +55 -0
  131. package/dist/terminal/index.d.ts +55 -0
  132. package/dist/terminal/index.js +4 -0
  133. package/dist/terminal/metafile-cjs.json +1 -0
  134. package/dist/terminal/metafile-esm.json +1 -0
  135. package/dist/ui/index.cjs +35 -0
  136. package/dist/ui/index.d.cts +298 -0
  137. package/dist/ui/index.d.ts +298 -0
  138. package/dist/ui/index.js +35 -0
  139. package/dist/ui/metafile-cjs.json +1 -0
  140. package/dist/ui/metafile-esm.json +1 -0
  141. package/dist/utils/index.cjs +23 -0
  142. package/dist/utils/index.d.cts +245 -0
  143. package/dist/utils/index.d.ts +245 -0
  144. package/dist/utils/index.js +23 -0
  145. package/dist/utils/metafile-cjs.json +1 -0
  146. package/dist/utils/metafile-esm.json +1 -0
  147. package/native/mxc/LICENSE.microsoft-mxc-sdk.md +21 -0
  148. package/native/mxc/README.md +25 -0
  149. package/native/mxc/bin/arm64/lxc-exec +0 -0
  150. package/native/mxc/bin/arm64/mxc-exec-mac +0 -0
  151. package/native/mxc/bin/arm64/wxc-exec.exe +0 -0
  152. package/native/mxc/bin/arm64/wxc-host-prep.exe +0 -0
  153. package/native/mxc/bin/x64/lxc-exec +0 -0
  154. package/native/mxc/bin/x64/wxc-exec.exe +0 -0
  155. package/native/mxc/bin/x64/wxc-host-prep.exe +0 -0
  156. package/native/mxc/package.json +58 -0
  157. package/ownership/CLEAN_ROOM_CONTRIBUTOR_GUIDE.md +63 -0
  158. package/ownership/audit.mjs +727 -0
  159. package/ownership/evidence/PROPRIETARY-COMMAND-1/implementation-record.md +77 -0
  160. package/ownership/evidence/PROPRIETARY-COMMAND-1/provenance-review.md +51 -0
  161. package/ownership/evidence/PROPRIETARY-MEDIA-1/implementation-record.md +131 -0
  162. package/ownership/evidence/PROPRIETARY-MEDIA-1/provenance-review.md +50 -0
  163. package/ownership/evidence/PROPRIETARY-PTY-1/implementation-record.md +86 -0
  164. package/ownership/evidence/PROPRIETARY-PTY-1/provenance-review.md +52 -0
  165. package/ownership/evidence/PROPRIETARY-RUNTIME-1/implementation-record.md +68 -0
  166. package/ownership/evidence/PROPRIETARY-RUNTIME-1/provenance-review.md +32 -0
  167. package/ownership/evidence/PROPRIETARY-TOOLCHAIN-1/implementation-record.md +53 -0
  168. package/ownership/evidence/PROPRIETARY-TOOLCHAIN-1/provenance-review.md +32 -0
  169. package/ownership/evidence/PROPRIETARY-UI-1/implementation-record.md +96 -0
  170. package/ownership/evidence/PROPRIETARY-UI-1/provenance-review.md +46 -0
  171. package/ownership/ownership-policy.json +232 -0
  172. package/ownership/ownership-policy.schema.json +192 -0
  173. package/ownership/templates/clean-room-implementation-record.md +70 -0
  174. package/ownership/templates/provenance-review.md +51 -0
  175. package/package.json +209 -0
@@ -0,0 +1,198 @@
1
+ type PermissionProfileName = "default" | "read-only" | "trusted-dev";
2
+ type PermissionProfileDecision = "allow" | "ask" | "deny";
3
+ type PermissionProfileMode = "default" | "acceptEdits" | "bypassPermissions" | "auto";
4
+ interface PermissionProfile {
5
+ schemaVersion: 1;
6
+ name: PermissionProfileName;
7
+ displayName: string;
8
+ description: string;
9
+ permissionMode: PermissionProfileMode;
10
+ filesystem: {
11
+ scope: "workspace" | "workspace-readonly" | "unrestricted";
12
+ read: PermissionProfileDecision;
13
+ write: PermissionProfileDecision;
14
+ allowedPaths: string[];
15
+ deniedPaths: string[];
16
+ };
17
+ shell: {
18
+ default: PermissionProfileDecision;
19
+ allowedCommands: string[];
20
+ deniedCommands: string[];
21
+ };
22
+ network: {
23
+ default: PermissionProfileDecision;
24
+ allowDomains: string[];
25
+ denyDomains: string[];
26
+ };
27
+ mcp: {
28
+ remoteServers: PermissionProfileDecision;
29
+ allowedServers: string[];
30
+ deniedServers: string[];
31
+ };
32
+ lsp: {
33
+ enabled: boolean;
34
+ diagnostics: PermissionProfileDecision;
35
+ navigation: PermissionProfileDecision;
36
+ startProcesses: PermissionProfileDecision;
37
+ };
38
+ }
39
+ type HookEventName = "SessionStart" | "UserPromptSubmit" | "PermissionRequest" | "PreToolUse" | "PostToolUse" | "PreCompact" | "PostCompact" | "Stop" | "StopFailure" | "SubagentStart" | "SubagentStop";
40
+ type HookPermissionMode = "default" | "plan" | "acceptEdits" | "auto" | "dontAsk" | "bypassPermissions";
41
+ interface HookInputBase {
42
+ schemaVersion: 1;
43
+ event: HookEventName;
44
+ sessionId: string;
45
+ runId: string;
46
+ rootRunId: string;
47
+ agentId: string;
48
+ agentName?: string;
49
+ agentColor?: string;
50
+ parentAgentId?: string;
51
+ cwd: string;
52
+ transcriptPath?: string;
53
+ permissionMode: HookPermissionMode;
54
+ model: string;
55
+ effort?: string;
56
+ timestamp: string;
57
+ }
58
+ interface HookInvocationInput extends HookInputBase {
59
+ prompt?: string;
60
+ toolName?: string;
61
+ toolInput?: Record<string, unknown>;
62
+ toolResult?: unknown;
63
+ finalText?: string;
64
+ metadata?: Record<string, unknown>;
65
+ }
66
+ type HookDecision = {
67
+ decision: "allow";
68
+ systemMessage?: string;
69
+ context?: string;
70
+ } | {
71
+ decision: "block";
72
+ reason: string;
73
+ systemMessage?: string;
74
+ } | {
75
+ decision: "ask";
76
+ reason: string;
77
+ prompt: string;
78
+ } | {
79
+ decision: "modify";
80
+ patch: unknown;
81
+ reason?: string;
82
+ } | {
83
+ decision: "continue";
84
+ context?: string;
85
+ systemMessage?: string;
86
+ };
87
+ interface BaseHookDefinition {
88
+ name?: string;
89
+ events?: HookEventName[];
90
+ timeoutMs?: number;
91
+ maxOutputBytes?: number;
92
+ failClosed?: boolean;
93
+ async?: boolean;
94
+ }
95
+ interface CommandHookDefinition extends BaseHookDefinition {
96
+ type: "command";
97
+ command: string;
98
+ args?: string[];
99
+ cwd?: string;
100
+ shell?: boolean;
101
+ env?: Record<string, string>;
102
+ }
103
+ interface HttpHookDefinition extends BaseHookDefinition {
104
+ type: "http";
105
+ url: string;
106
+ method?: "POST";
107
+ headers?: Record<string, string>;
108
+ }
109
+ interface PromptHookDefinition extends BaseHookDefinition {
110
+ type: "prompt";
111
+ prompt: string;
112
+ }
113
+ interface AgentHookDefinition extends BaseHookDefinition {
114
+ type: "agent";
115
+ prompt: string;
116
+ agent?: string;
117
+ model?: string;
118
+ }
119
+ type HookDefinition = CommandHookDefinition | HttpHookDefinition | PromptHookDefinition | AgentHookDefinition;
120
+ type HookInput = HookInvocationInput;
121
+ interface HookConfig {
122
+ hooks?: HookDefinition[];
123
+ events?: Partial<Record<HookEventName, HookDefinition[]>>;
124
+ }
125
+ type HookModelExecutor = (definition: PromptHookDefinition | AgentHookDefinition, input: HookInvocationInput) => HookDecision | Promise<HookDecision>;
126
+ type HookExecutionStatus = "allowed" | "blocked" | "asked" | "modified" | "continued" | "errored" | "timed_out";
127
+ interface HookExecutionResult {
128
+ hook: HookDefinition;
129
+ status: HookExecutionStatus;
130
+ decision?: HookDecision;
131
+ exitCode?: number | null;
132
+ signal?: NodeJS.Signals | null;
133
+ stdout: string;
134
+ stderr: string;
135
+ stdoutTruncated: boolean;
136
+ stderrTruncated: boolean;
137
+ timedOut: boolean;
138
+ durationMs: number;
139
+ error?: string;
140
+ }
141
+ interface HookRunResult {
142
+ decision: HookDecision;
143
+ results: HookExecutionResult[];
144
+ context: string[];
145
+ systemMessages: string[];
146
+ }
147
+ interface HookRuntimeOptions {
148
+ defaultTimeoutMs?: number;
149
+ defaultMaxOutputBytes?: number;
150
+ env?: NodeJS.ProcessEnv;
151
+ permissionProfile?: PermissionProfile;
152
+ promptExecutor?: HookModelExecutor;
153
+ agentExecutor?: HookModelExecutor;
154
+ }
155
+ declare function normalizeHookDecision(value: unknown): HookDecision;
156
+ declare function buildHookEnvironment(input: HookInvocationInput, definition: CommandHookDefinition, sourceEnv?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
157
+ declare function hookResultStatus(decision: HookDecision | undefined): HookExecutionResult["status"];
158
+ declare function runCommandHook(definition: CommandHookDefinition, input: HookInvocationInput, options?: HookRuntimeOptions): Promise<HookExecutionResult>;
159
+ declare function runHttpHook(definition: HttpHookDefinition, input: HookInvocationInput, options?: HookRuntimeOptions): Promise<HookExecutionResult>;
160
+ declare function runPromptHook(definition: PromptHookDefinition, input: HookInvocationInput, options?: HookRuntimeOptions): Promise<HookExecutionResult>;
161
+ declare function runAgentHook(definition: AgentHookDefinition, input: HookInvocationInput, options?: HookRuntimeOptions): Promise<HookExecutionResult>;
162
+ declare class PromptHookRunner {
163
+ private readonly executor;
164
+ private readonly options;
165
+ constructor(executor: HookModelExecutor, options?: HookRuntimeOptions);
166
+ run(definition: PromptHookDefinition, input: HookInvocationInput): Promise<HookExecutionResult>;
167
+ }
168
+ declare class AgentHookRunner {
169
+ private readonly executor;
170
+ private readonly options;
171
+ constructor(executor: HookModelExecutor, options?: HookRuntimeOptions);
172
+ run(definition: AgentHookDefinition, input: HookInvocationInput): Promise<HookExecutionResult>;
173
+ }
174
+ declare function runHookDefinition(hook: HookDefinition, input: HookInvocationInput, options?: HookRuntimeOptions): Promise<HookExecutionResult>;
175
+ declare function runHooks(hooks: readonly HookDefinition[], input: HookInvocationInput, options?: HookRuntimeOptions): Promise<HookRunResult>;
176
+ declare class HookRunner {
177
+ private readonly hooks;
178
+ private readonly options;
179
+ constructor(hooks: readonly HookDefinition[], options?: HookRuntimeOptions);
180
+ run(input: HookInvocationInput): Promise<HookRunResult>;
181
+ }
182
+ declare class HookRuntime {
183
+ private readonly config;
184
+ private readonly options;
185
+ constructor(config: HookConfig, options?: HookRuntimeOptions);
186
+ run(input: HookInvocationInput): Promise<HookRunResult>;
187
+ }
188
+ declare class CommandHookRunner {
189
+ private readonly options;
190
+ constructor(options?: HookRuntimeOptions);
191
+ run(definition: CommandHookDefinition, input: HookInvocationInput): Promise<HookExecutionResult>;
192
+ }
193
+ declare class HttpHookRunner {
194
+ private readonly options;
195
+ constructor(options?: HookRuntimeOptions);
196
+ run(definition: HttpHookDefinition, input: HookInvocationInput): Promise<HookExecutionResult>;
197
+ }
198
+ export { type AgentHookDefinition, AgentHookRunner, type BaseHookDefinition, type CommandHookDefinition, CommandHookRunner, type HookConfig, type HookDecision, type HookDefinition, type HookEventName, type HookExecutionResult, type HookExecutionStatus, type HookInput, type HookInputBase, type HookInvocationInput, type HookModelExecutor, type HookPermissionMode, type HookRunResult, HookRunner, HookRuntime, type HookRuntimeOptions, type HttpHookDefinition, HttpHookRunner, type PromptHookDefinition, PromptHookRunner, buildHookEnvironment, hookResultStatus, normalizeHookDecision, runAgentHook, runCommandHook, runHookDefinition, runHooks, runHttpHook, runPromptHook };
@@ -0,0 +1,198 @@
1
+ type PermissionProfileName = "default" | "read-only" | "trusted-dev";
2
+ type PermissionProfileDecision = "allow" | "ask" | "deny";
3
+ type PermissionProfileMode = "default" | "acceptEdits" | "bypassPermissions" | "auto";
4
+ interface PermissionProfile {
5
+ schemaVersion: 1;
6
+ name: PermissionProfileName;
7
+ displayName: string;
8
+ description: string;
9
+ permissionMode: PermissionProfileMode;
10
+ filesystem: {
11
+ scope: "workspace" | "workspace-readonly" | "unrestricted";
12
+ read: PermissionProfileDecision;
13
+ write: PermissionProfileDecision;
14
+ allowedPaths: string[];
15
+ deniedPaths: string[];
16
+ };
17
+ shell: {
18
+ default: PermissionProfileDecision;
19
+ allowedCommands: string[];
20
+ deniedCommands: string[];
21
+ };
22
+ network: {
23
+ default: PermissionProfileDecision;
24
+ allowDomains: string[];
25
+ denyDomains: string[];
26
+ };
27
+ mcp: {
28
+ remoteServers: PermissionProfileDecision;
29
+ allowedServers: string[];
30
+ deniedServers: string[];
31
+ };
32
+ lsp: {
33
+ enabled: boolean;
34
+ diagnostics: PermissionProfileDecision;
35
+ navigation: PermissionProfileDecision;
36
+ startProcesses: PermissionProfileDecision;
37
+ };
38
+ }
39
+ type HookEventName = "SessionStart" | "UserPromptSubmit" | "PermissionRequest" | "PreToolUse" | "PostToolUse" | "PreCompact" | "PostCompact" | "Stop" | "StopFailure" | "SubagentStart" | "SubagentStop";
40
+ type HookPermissionMode = "default" | "plan" | "acceptEdits" | "auto" | "dontAsk" | "bypassPermissions";
41
+ interface HookInputBase {
42
+ schemaVersion: 1;
43
+ event: HookEventName;
44
+ sessionId: string;
45
+ runId: string;
46
+ rootRunId: string;
47
+ agentId: string;
48
+ agentName?: string;
49
+ agentColor?: string;
50
+ parentAgentId?: string;
51
+ cwd: string;
52
+ transcriptPath?: string;
53
+ permissionMode: HookPermissionMode;
54
+ model: string;
55
+ effort?: string;
56
+ timestamp: string;
57
+ }
58
+ interface HookInvocationInput extends HookInputBase {
59
+ prompt?: string;
60
+ toolName?: string;
61
+ toolInput?: Record<string, unknown>;
62
+ toolResult?: unknown;
63
+ finalText?: string;
64
+ metadata?: Record<string, unknown>;
65
+ }
66
+ type HookDecision = {
67
+ decision: "allow";
68
+ systemMessage?: string;
69
+ context?: string;
70
+ } | {
71
+ decision: "block";
72
+ reason: string;
73
+ systemMessage?: string;
74
+ } | {
75
+ decision: "ask";
76
+ reason: string;
77
+ prompt: string;
78
+ } | {
79
+ decision: "modify";
80
+ patch: unknown;
81
+ reason?: string;
82
+ } | {
83
+ decision: "continue";
84
+ context?: string;
85
+ systemMessage?: string;
86
+ };
87
+ interface BaseHookDefinition {
88
+ name?: string;
89
+ events?: HookEventName[];
90
+ timeoutMs?: number;
91
+ maxOutputBytes?: number;
92
+ failClosed?: boolean;
93
+ async?: boolean;
94
+ }
95
+ interface CommandHookDefinition extends BaseHookDefinition {
96
+ type: "command";
97
+ command: string;
98
+ args?: string[];
99
+ cwd?: string;
100
+ shell?: boolean;
101
+ env?: Record<string, string>;
102
+ }
103
+ interface HttpHookDefinition extends BaseHookDefinition {
104
+ type: "http";
105
+ url: string;
106
+ method?: "POST";
107
+ headers?: Record<string, string>;
108
+ }
109
+ interface PromptHookDefinition extends BaseHookDefinition {
110
+ type: "prompt";
111
+ prompt: string;
112
+ }
113
+ interface AgentHookDefinition extends BaseHookDefinition {
114
+ type: "agent";
115
+ prompt: string;
116
+ agent?: string;
117
+ model?: string;
118
+ }
119
+ type HookDefinition = CommandHookDefinition | HttpHookDefinition | PromptHookDefinition | AgentHookDefinition;
120
+ type HookInput = HookInvocationInput;
121
+ interface HookConfig {
122
+ hooks?: HookDefinition[];
123
+ events?: Partial<Record<HookEventName, HookDefinition[]>>;
124
+ }
125
+ type HookModelExecutor = (definition: PromptHookDefinition | AgentHookDefinition, input: HookInvocationInput) => HookDecision | Promise<HookDecision>;
126
+ type HookExecutionStatus = "allowed" | "blocked" | "asked" | "modified" | "continued" | "errored" | "timed_out";
127
+ interface HookExecutionResult {
128
+ hook: HookDefinition;
129
+ status: HookExecutionStatus;
130
+ decision?: HookDecision;
131
+ exitCode?: number | null;
132
+ signal?: NodeJS.Signals | null;
133
+ stdout: string;
134
+ stderr: string;
135
+ stdoutTruncated: boolean;
136
+ stderrTruncated: boolean;
137
+ timedOut: boolean;
138
+ durationMs: number;
139
+ error?: string;
140
+ }
141
+ interface HookRunResult {
142
+ decision: HookDecision;
143
+ results: HookExecutionResult[];
144
+ context: string[];
145
+ systemMessages: string[];
146
+ }
147
+ interface HookRuntimeOptions {
148
+ defaultTimeoutMs?: number;
149
+ defaultMaxOutputBytes?: number;
150
+ env?: NodeJS.ProcessEnv;
151
+ permissionProfile?: PermissionProfile;
152
+ promptExecutor?: HookModelExecutor;
153
+ agentExecutor?: HookModelExecutor;
154
+ }
155
+ declare function normalizeHookDecision(value: unknown): HookDecision;
156
+ declare function buildHookEnvironment(input: HookInvocationInput, definition: CommandHookDefinition, sourceEnv?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
157
+ declare function hookResultStatus(decision: HookDecision | undefined): HookExecutionResult["status"];
158
+ declare function runCommandHook(definition: CommandHookDefinition, input: HookInvocationInput, options?: HookRuntimeOptions): Promise<HookExecutionResult>;
159
+ declare function runHttpHook(definition: HttpHookDefinition, input: HookInvocationInput, options?: HookRuntimeOptions): Promise<HookExecutionResult>;
160
+ declare function runPromptHook(definition: PromptHookDefinition, input: HookInvocationInput, options?: HookRuntimeOptions): Promise<HookExecutionResult>;
161
+ declare function runAgentHook(definition: AgentHookDefinition, input: HookInvocationInput, options?: HookRuntimeOptions): Promise<HookExecutionResult>;
162
+ declare class PromptHookRunner {
163
+ private readonly executor;
164
+ private readonly options;
165
+ constructor(executor: HookModelExecutor, options?: HookRuntimeOptions);
166
+ run(definition: PromptHookDefinition, input: HookInvocationInput): Promise<HookExecutionResult>;
167
+ }
168
+ declare class AgentHookRunner {
169
+ private readonly executor;
170
+ private readonly options;
171
+ constructor(executor: HookModelExecutor, options?: HookRuntimeOptions);
172
+ run(definition: AgentHookDefinition, input: HookInvocationInput): Promise<HookExecutionResult>;
173
+ }
174
+ declare function runHookDefinition(hook: HookDefinition, input: HookInvocationInput, options?: HookRuntimeOptions): Promise<HookExecutionResult>;
175
+ declare function runHooks(hooks: readonly HookDefinition[], input: HookInvocationInput, options?: HookRuntimeOptions): Promise<HookRunResult>;
176
+ declare class HookRunner {
177
+ private readonly hooks;
178
+ private readonly options;
179
+ constructor(hooks: readonly HookDefinition[], options?: HookRuntimeOptions);
180
+ run(input: HookInvocationInput): Promise<HookRunResult>;
181
+ }
182
+ declare class HookRuntime {
183
+ private readonly config;
184
+ private readonly options;
185
+ constructor(config: HookConfig, options?: HookRuntimeOptions);
186
+ run(input: HookInvocationInput): Promise<HookRunResult>;
187
+ }
188
+ declare class CommandHookRunner {
189
+ private readonly options;
190
+ constructor(options?: HookRuntimeOptions);
191
+ run(definition: CommandHookDefinition, input: HookInvocationInput): Promise<HookExecutionResult>;
192
+ }
193
+ declare class HttpHookRunner {
194
+ private readonly options;
195
+ constructor(options?: HookRuntimeOptions);
196
+ run(definition: HttpHookDefinition, input: HookInvocationInput): Promise<HookExecutionResult>;
197
+ }
198
+ export { type AgentHookDefinition, AgentHookRunner, type BaseHookDefinition, type CommandHookDefinition, CommandHookRunner, type HookConfig, type HookDecision, type HookDefinition, type HookEventName, type HookExecutionResult, type HookExecutionStatus, type HookInput, type HookInputBase, type HookInvocationInput, type HookModelExecutor, type HookPermissionMode, type HookRunResult, HookRunner, HookRuntime, type HookRuntimeOptions, type HttpHookDefinition, HttpHookRunner, type PromptHookDefinition, PromptHookRunner, buildHookEnvironment, hookResultStatus, normalizeHookDecision, runAgentHook, runCommandHook, runHookDefinition, runHooks, runHttpHook, runPromptHook };
@@ -0,0 +1,9 @@
1
+ import{spawn as X}from"node:child_process";var q=3e4,Y=64*1024,Z=/(^|_)(TOKEN|SECRET|PASSWORD|PASS|KEY|CREDENTIAL|COOKIE|AUTH|AUTHORIZATION)(_|$)/i,Q=new Set(["PATH","Path","PATHEXT","SystemRoot","WINDIR","ComSpec","TMP","TEMP","HOME","USERPROFILE"]);function v(){return Date.now()}function U(e,o){return!Number.isFinite(e)||e===void 0?o:Math.max(1,Math.floor(e))}function j(e,o,t){if(Buffer.byteLength(e)>=t)return{value:e,truncated:!0};let n=e+o.toString("utf8");return Buffer.byteLength(n)<=t?{value:n,truncated:!1}:{value:Buffer.from(n,"utf8").subarray(0,t).toString("utf8"),truncated:!0}}function M(e){return e.replace(/\r\n/g,`
2
+ `).split(`
3
+ `).map(o=>o.trim()).find(o=>o.length>0)}function D(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("Hook stdout JSON must be an object");let o=e,t=o.decision;if(t==="allow")return{decision:t,...typeof o.systemMessage=="string"?{systemMessage:o.systemMessage}:{},...typeof o.context=="string"?{context:o.context}:{}};if(t==="block"){let n=typeof o.reason=="string"&&o.reason.trim()?o.reason.trim():"Hook blocked the operation";return{decision:t,reason:n,...typeof o.systemMessage=="string"?{systemMessage:o.systemMessage}:{}}}if(t==="ask"){let n=typeof o.reason=="string"&&o.reason.trim()?o.reason.trim():"Hook requested user confirmation",r=typeof o.prompt=="string"&&o.prompt.trim()?o.prompt.trim():n;return{decision:t,reason:n,prompt:r}}if(t==="modify")return{decision:t,patch:o.patch,...typeof o.reason=="string"?{reason:o.reason}:{}};if(t==="continue")return{decision:t,...typeof o.context=="string"?{context:o.context}:{},...typeof o.systemMessage=="string"?{systemMessage:o.systemMessage}:{}};throw new Error(`Unsupported hook decision: ${String(t)}`)}function ee(e){let o=e.trim();if(o)return D(JSON.parse(o))}function F(e,o,t=process.env){let n={};for(let[r,s]of Object.entries(t))s!==void 0&&(!Q.has(r)&&Z.test(r)||(n[r]=s));for(let[r,s]of Object.entries(o.env??{}))n[r]=s;return n.XENO_PROJECT_DIR=e.cwd,n.XENO_SESSION_ID=e.sessionId,n.XENO_RUN_ID=e.runId,n.XENO_ROOT_RUN_ID=e.rootRunId,n.XENO_AGENT_ID=e.agentId,n.XENO_HOOK_EVENT=e.event,n.XENO_PERMISSION_MODE=e.permissionMode,n.XENO_MODEL=e.model,e.effort&&(n.XENO_EFFORT=e.effort),e.parentAgentId&&(n.XENO_PARENT_AGENT_ID=e.parentAgentId),e.transcriptPath&&(n.XENO_TRANSCRIPT_PATH=e.transcriptPath),n}function oe(e){if(process.platform==="win32"){X("taskkill",["/PID",String(e),"/T","/F"],{stdio:"ignore",windowsHide:!0}).on("error",()=>{});return}try{process.kill(-e,"SIGTERM")}catch{try{process.kill(e,"SIGTERM")}catch{return}}setTimeout(()=>{try{process.kill(-e,"SIGKILL")}catch{try{process.kill(e,"SIGKILL")}catch{}}},1e3).unref()}function H(e){return e?e.decision==="block"?"blocked":e.decision==="ask"?"asked":e.decision==="modify"?"modified":e.decision==="continue"?"continued":"allowed":"allowed"}async function E(e,o,t={}){let n=v(),r=U(e.timeoutMs??t.defaultTimeoutMs,q),s=U(e.maxOutputBytes??t.defaultMaxOutputBytes,Y),u=F(o,e,t.env),i=e.cwd??o.cwd;return new Promise(l=>{let a="",c="",p=!1,d=!1,k=!1,w=!1,y=X(e.command,e.args??[],{cwd:i,env:u,shell:e.shell??!1,detached:process.platform!=="win32",windowsHide:!0,stdio:["pipe","pipe","pipe"]}),O=f=>{w||(w=!0,clearTimeout(W),l(f))},W=setTimeout(()=>{k=!0,y.pid&&oe(y.pid)},r);y.stdout.on("data",f=>{let m=j(a,f,s);a=m.value,p=p||m.truncated}),y.stderr.on("data",f=>{let m=j(c,f,s);c=m.value,d=d||m.truncated}),y.on("error",f=>{let m=e.failClosed?{decision:"block",reason:`Hook command failed: ${f.message}`}:void 0;O({hook:e,status:m?H(m):"errored",...m?{decision:m}:{},stdout:a,stderr:c,stdoutTruncated:p,stderrTruncated:d,timedOut:k,durationMs:v()-n,error:f.message})}),y.on("close",(f,m)=>{if(k){let g=e.failClosed?{decision:"block",reason:`Hook timed out after ${r}ms`}:void 0;O({hook:e,status:g?H(g):"timed_out",...g?{decision:g}:{},exitCode:f,signal:m,stdout:a,stderr:c,stdoutTruncated:p,stderrTruncated:d,timedOut:k,durationMs:v()-n,error:`Hook timed out after ${r}ms`});return}let P,h;if(f===0)try{P=ee(a)}catch(g){h=g instanceof Error?g.message:String(g),e.failClosed&&(P={decision:"block",reason:`Invalid hook output: ${h}`})}else f===2?P={decision:"block",reason:M(a)??M(c)??"Hook blocked the operation"}:e.failClosed&&(P={decision:"block",reason:M(c)??`Hook exited with code ${f??"unknown"}`});O({hook:e,status:h&&!P?"errored":H(P),...P?{decision:P}:{},exitCode:f,signal:m,stdout:a,stderr:c,stdoutTruncated:p,stderrTruncated:d,timedOut:k,durationMs:v()-n,...h?{error:h}:{}})}),y.stdin.end(JSON.stringify(o))})}function te(e){return e.trim().toLowerCase().replace(/\.+$/,"")}function J(e,o){let t=te(o);if(!t)return!1;if(t==="*")return!0;if(t.startsWith("*.")){let n=t.slice(2);return e===n||e.endsWith(`.${n}`)}return e===t||e.endsWith(`.${t}`)}function z(e,o){let t;try{t=new URL(o).hostname.toLowerCase().replace(/\.+$/,"")}catch{return{decision:"deny",allowed:!1,hostname:null,matchedDomain:null,reason:"network policy denied malformed URL"}}let n=e.network.denyDomains.find(s=>J(t,s));if(n)return{decision:"deny",allowed:!1,hostname:t,matchedDomain:n,reason:`network policy denied ${t} by ${n}`};let r=e.network.allowDomains.find(s=>J(t,s));return r?{decision:"allow",allowed:!0,hostname:t,matchedDomain:r,reason:`network policy allowed ${t} by ${r}`}:{decision:e.network.default,allowed:e.network.default!=="deny",hostname:t,matchedDomain:null,reason:`network policy default ${e.network.default} for ${t}`}}var ne=3e4,re=64*1024;function b(){return Date.now()}function K(e,o){return!Number.isFinite(e)||e===void 0?o:Math.max(1,Math.floor(e))}function V(e,o,t){if(Buffer.byteLength(e)>=t)return{value:e,truncated:!0};let n=e+o.toString("utf8");return Buffer.byteLength(n)<=t?{value:n,truncated:!1}:{value:Buffer.from(n,"utf8").subarray(0,t).toString("utf8"),truncated:!0}}function se(e){return e.replace(/\r\n/g,`
4
+ `).split(`
5
+ `).map(o=>o.trim()).find(o=>o.length>0)}function ie(e){let o=e.trim();if(o)return D(JSON.parse(o))}async function ae(e,o){if(!e.body){let s=await e.text(),u=V("",Buffer.from(s,"utf8"),o);return{stdout:u.value,stdoutTruncated:u.truncated}}let t=e.body.getReader(),n="",r=!1;try{for(;;){let{done:s,value:u}=await t.read();if(s)break;let i=V(n,Buffer.from(u),o);if(n=i.value,r=r||i.truncated,r){await t.cancel();break}}}finally{t.releaseLock()}return{stdout:n,stdoutTruncated:r}}function ue(e,o){let t=new Headers(e.headers??{});return t.has("content-type")||t.set("content-type","application/json"),t.has("accept")||t.set("accept","application/json"),t.set("x-xeno-hook-event",o.event),t.set("x-xeno-session-id",o.sessionId),t.set("x-xeno-run-id",o.runId),t}function ce(e,o){if(!o.permissionProfile)return;let t=z(o.permissionProfile,e.url);if(!t.allowed)throw new Error(`HTTP hook network policy denied: ${t.reason}`)}async function x(e,o,t={}){let n=b(),r=K(e.timeoutMs??t.defaultTimeoutMs,ne),s=K(e.maxOutputBytes??t.defaultMaxOutputBytes,re),u=new AbortController,i=!1,l=setTimeout(()=>{i=!0,u.abort()},r);try{ce(e,t);let a=await fetch(e.url,{method:e.method??"POST",headers:ue(e,o),body:JSON.stringify(o),signal:u.signal}),{stdout:c,stdoutTruncated:p}=await ae(a,s),d,k;if(a.ok)try{d=ie(c)}catch(w){k=w instanceof Error?w.message:String(w),e.failClosed&&(d={decision:"block",reason:`Invalid HTTP hook output: ${k}`})}else e.failClosed&&(d={decision:"block",reason:se(c)??`HTTP hook failed with status ${a.status}`});return{hook:e,status:k&&!d?"errored":a.ok||d?H(d):"errored",...d?{decision:d}:{},stdout:c,stderr:"",stdoutTruncated:p,stderrTruncated:!1,timedOut:i,durationMs:b()-n,...a.ok?{}:{error:`HTTP ${a.status} ${a.statusText}`.trim()},...k?{error:k}:{}}}catch(a){let c=a instanceof Error?a.message:String(a),p=e.failClosed?{decision:"block",reason:i?`HTTP hook timed out after ${r}ms`:`HTTP hook failed: ${c}`}:void 0;return{hook:e,status:p?H(p):i?"timed_out":"errored",...p?{decision:p}:{},stdout:"",stderr:"",stdoutTruncated:!1,stderrTruncated:!1,timedOut:i,durationMs:b()-n,error:i?`HTTP hook timed out after ${r}ms`:c}}finally{clearTimeout(l)}}import{performance as T}from"node:perf_hooks";async function G(e,o,t,n){let r=T.now();if(!t){let i=`No ${e.type} hook executor is configured.`,l=e.failClosed?{decision:"block",reason:i}:void 0;return{hook:e,status:l?H(l):"errored",...l?{decision:l}:{},stdout:"",stderr:i,stdoutTruncated:!1,stderrTruncated:!1,timedOut:!1,durationMs:T.now()-r,error:i}}let s=Math.max(1,Math.trunc(e.timeoutMs??n.defaultTimeoutMs??3e4)),u;try{let i=await Promise.race([t(e,o),new Promise((l,a)=>{u=setTimeout(()=>a(new Error(`Hook timed out after ${s}ms`)),s),u.unref?.()})]);return{hook:e,status:H(i),decision:i,stdout:JSON.stringify(i),stderr:"",stdoutTruncated:!1,stderrTruncated:!1,timedOut:!1,durationMs:T.now()-r}}catch(i){let l=i instanceof Error?i.message:String(i),a=/timed out/i.test(l),c=e.failClosed?{decision:"block",reason:l}:void 0;return{hook:e,status:c?H(c):a?"timed_out":"errored",...c?{decision:c}:{},stdout:"",stderr:l,stdoutTruncated:!1,stderrTruncated:!1,timedOut:a,durationMs:T.now()-r,error:l}}finally{u&&clearTimeout(u)}}function R(e,o,t={}){return G(e,o,t.promptExecutor,t)}function I(e,o,t={}){return G(e,o,t.agentExecutor,t)}var S=class{constructor(o,t={}){this.executor=o;this.options=t}executor;options;run(o,t){return R(o,t,{...this.options,promptExecutor:this.executor})}},N=class{constructor(o,t={}){this.executor=o;this.options=t}executor;options;run(o,t){return I(o,t,{...this.options,agentExecutor:this.executor})}};function le(e,o){return!e.events||e.events.length===0||e.events.includes(o)}function de(e,o,t){e&&("context"in e&&typeof e.context=="string"&&e.context.trim()&&o.push(e.context.trim()),"systemMessage"in e&&typeof e.systemMessage=="string"&&e.systemMessage.trim()&&t.push(e.systemMessage.trim()))}function fe(e){return e&&(e.decision==="block"||e.decision==="ask"||e.decision==="modify")?e:null}async function _(e,o,t={}){switch(e.type){case"command":return E(e,o,t);case"http":return x(e,o,t);case"prompt":return R(e,o,t);case"agent":return I(e,o,t);default:throw new Error(`Unsupported hook type: ${String(e.type??"unknown")}`)}}async function B(e,o,t={}){let n=[],r=[],s=[];for(let u of e){if(!le(u,o.event))continue;if(u.async){_(u,o,t).catch(()=>{});continue}let i=await _(u,o,t);n.push(i),de(i.decision,r,s);let l=fe(i.decision);if(l)return{decision:l,results:n,context:r,systemMessages:s}}return{decision:r.length>0||s.length>0?{decision:"continue",...r.length>0?{context:r.join(`
6
+
7
+ `)}:{},...s.length>0?{systemMessage:s.join(`
8
+
9
+ `)}:{}}:{decision:"allow"},results:n,context:r,systemMessages:s}}var A=class{constructor(o,t={}){this.hooks=o;this.options=t}hooks;options;run(o){return B(this.hooks,o,this.options)}},C=class{constructor(o,t={}){this.config=o;this.options=t}config;options;run(o){let t=[...this.config.hooks??[],...this.config.events?.[o.event]??[]];return B([...new Set(t)],o,this.options)}},$=class{constructor(o={}){this.options=o}options;run(o,t){return E(o,t,this.options)}},L=class{constructor(o={}){this.options=o}options;run(o,t){return x(o,t,this.options)}};export{N as AgentHookRunner,$ as CommandHookRunner,A as HookRunner,C as HookRuntime,L as HttpHookRunner,S as PromptHookRunner,F as buildHookEnvironment,H as hookResultStatus,D as normalizeHookDecision,I as runAgentHook,E as runCommandHook,_ as runHookDefinition,B as runHooks,x as runHttpHook,R as runPromptHook};
@@ -0,0 +1 @@
1
+ {"inputs":{"src/hooks/command-hook.ts":{"bytes":10057,"imports":[{"path":"node:child_process","kind":"import-statement","external":true}],"format":"esm"},"src/security/permission-profile.ts":{"bytes":8013,"imports":[],"format":"esm"},"src/hooks/http-hook.ts":{"bytes":6327,"imports":[{"path":"src/hooks/command-hook.ts","kind":"import-statement","original":"./command-hook.js"},{"path":"src/security/permission-profile.ts","kind":"import-statement","original":"../security/permission-profile.js"}],"format":"esm"},"src/hooks/model-hook.ts":{"bytes":3834,"imports":[{"path":"node:perf_hooks","kind":"import-statement","external":true},{"path":"src/hooks/command-hook.ts","kind":"import-statement","original":"./command-hook.js"}],"format":"esm"},"src/hooks/runner.ts":{"bytes":4461,"imports":[{"path":"src/hooks/command-hook.ts","kind":"import-statement","original":"./command-hook.js"},{"path":"src/hooks/http-hook.ts","kind":"import-statement","original":"./http-hook.js"},{"path":"src/hooks/model-hook.ts","kind":"import-statement","original":"./model-hook.js"}],"format":"esm"},"src/hooks/index.ts":{"bytes":860,"imports":[{"path":"src/hooks/command-hook.ts","kind":"import-statement","original":"./command-hook.js"},{"path":"src/hooks/http-hook.ts","kind":"import-statement","original":"./http-hook.js"},{"path":"src/hooks/model-hook.ts","kind":"import-statement","original":"./model-hook.js"},{"path":"src/hooks/runner.ts","kind":"import-statement","original":"./runner.js"}],"format":"esm"}},"outputs":{"dist/hooks/index.cjs":{"imports":[{"path":"node:child_process","kind":"require-call","external":true},{"path":"node:perf_hooks","kind":"require-call","external":true}],"exports":[],"entryPoint":"src/hooks/index.ts","inputs":{"src/hooks/index.ts":{"bytesInOutput":361},"src/hooks/command-hook.ts":{"bytesInOutput":4530},"src/security/permission-profile.ts":{"bytesInOutput":902},"src/hooks/http-hook.ts":{"bytesInOutput":2575},"src/hooks/model-hook.ts":{"bytesInOutput":1468},"src/hooks/runner.ts":{"bytesInOutput":1584}},"bytes":12102}}}
@@ -0,0 +1 @@
1
+ {"inputs":{"src/hooks/command-hook.ts":{"bytes":10057,"imports":[{"path":"node:child_process","kind":"import-statement","external":true}],"format":"esm"},"src/security/permission-profile.ts":{"bytes":8013,"imports":[],"format":"esm"},"src/hooks/http-hook.ts":{"bytes":6327,"imports":[{"path":"src/hooks/command-hook.ts","kind":"import-statement","original":"./command-hook.js"},{"path":"src/security/permission-profile.ts","kind":"import-statement","original":"../security/permission-profile.js"}],"format":"esm"},"src/hooks/model-hook.ts":{"bytes":3834,"imports":[{"path":"node:perf_hooks","kind":"import-statement","external":true},{"path":"src/hooks/command-hook.ts","kind":"import-statement","original":"./command-hook.js"}],"format":"esm"},"src/hooks/runner.ts":{"bytes":4461,"imports":[{"path":"src/hooks/command-hook.ts","kind":"import-statement","original":"./command-hook.js"},{"path":"src/hooks/http-hook.ts","kind":"import-statement","original":"./http-hook.js"},{"path":"src/hooks/model-hook.ts","kind":"import-statement","original":"./model-hook.js"}],"format":"esm"},"src/hooks/index.ts":{"bytes":860,"imports":[{"path":"src/hooks/command-hook.ts","kind":"import-statement","original":"./command-hook.js"},{"path":"src/hooks/http-hook.ts","kind":"import-statement","original":"./http-hook.js"},{"path":"src/hooks/model-hook.ts","kind":"import-statement","original":"./model-hook.js"},{"path":"src/hooks/runner.ts","kind":"import-statement","original":"./runner.js"}],"format":"esm"}},"outputs":{"dist/hooks/index.js":{"imports":[{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:perf_hooks","kind":"import-statement","external":true}],"exports":["AgentHookRunner","CommandHookRunner","HookRunner","HookRuntime","HttpHookRunner","PromptHookRunner","buildHookEnvironment","hookResultStatus","normalizeHookDecision","runAgentHook","runCommandHook","runHookDefinition","runHooks","runHttpHook","runPromptHook"],"entryPoint":"src/hooks/index.ts","inputs":{"src/hooks/command-hook.ts":{"bytesInOutput":4513},"src/hooks/index.ts":{"bytesInOutput":0},"src/security/permission-profile.ts":{"bytesInOutput":902},"src/hooks/http-hook.ts":{"bytesInOutput":2575},"src/hooks/model-hook.ts":{"bytesInOutput":1433},"src/hooks/runner.ts":{"bytesInOutput":1584}},"bytes":11321}}}
@@ -0,0 +1 @@
1
+ "use strict";var C=Object.defineProperty;var de=Object.getOwnPropertyDescriptor;var ue=Object.getOwnPropertyNames;var le=Object.prototype.hasOwnProperty;var me=(e,t)=>{for(var r in t)C(e,r,{get:t[r],enumerable:!0})},pe=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ue(t))!le.call(e,o)&&o!==r&&C(e,o,{get:()=>t[o],enumerable:!(n=de(t,o))||n.enumerable});return e};var fe=e=>pe(C({},"__esModule",{value:!0}),e);var Fe={};me(Fe,{XENO_HOSTED_CONTROL_SCHEMA_VERSION:()=>B,XENO_HOSTED_ENVIRONMENT_SCHEMA_VERSION:()=>b,XENO_HOSTED_EVENT_SCHEMA_VERSION:()=>N,XENO_HOSTED_EXECUTION_ADAPTER_CERTIFICATION_SCHEMA:()=>E,XENO_HOSTED_EXECUTION_ADAPTER_MAX_CERTIFICATE_LIFETIME_MS:()=>Z,XENO_HOSTED_EXECUTION_ADAPTER_PROTOCOL_VERSION:()=>$,XENO_HOSTED_EXECUTION_PROTOCOL_VERSION:()=>ee,XENO_HOSTED_EXECUTION_TOOL_NAMES:()=>te,XENO_HOSTED_RESULT_SCHEMA_VERSION:()=>J,XENO_HOSTED_RUN_SCHEMA_VERSION:()=>Ze,XENO_HOSTED_TRIGGER_SCHEMA_VERSION:()=>Ge,assertValidXenoHostedExecutionJob:()=>Ne,createXenoHostedControlCommand:()=>ie,createXenoHostedEnvironmentManifest:()=>ge,createXenoHostedEvent:()=>he,createXenoHostedExecutionBoundaryReceipt:()=>re,createXenoHostedRunResult:()=>ae,deriveHostedIdempotencyKey:()=>Ee,hostedEnvironmentIdentity:()=>we,normalizeXenoHostedControlAcknowledgement:()=>ze,verifyXenoHostedControlCommand:()=>Je,verifyXenoHostedEnvironmentManifest:()=>k,verifyXenoHostedEventChain:()=>ye,verifyXenoHostedExecutionAdapterCertification:()=>Te,verifyXenoHostedExecutionJob:()=>ne,verifyXenoHostedRunResult:()=>Le,verifyXenoHostedWebhook:()=>Re,xenoHostedExecutionAdapterSigningPayload:()=>Ae});module.exports=fe(Fe);var b=1,Ze=1,N=1,Ge=1;var w=require("node:crypto");function u(e){return JSON.stringify(V(e,new Set))}function V(e,t){if(e===null||typeof e!="object"){if(typeof e=="number"&&!Number.isFinite(e))throw new TypeError("Artifact JSON cannot contain non-finite numbers");return e}if(t.has(e))throw new TypeError("Artifact JSON cannot contain cycles");if(t.add(e),Array.isArray(e)){let n=e.map(o=>V(o,t));return t.delete(e),n}let r={};for(let n of Object.keys(e).sort((o,s)=>o.localeCompare(s))){let o=e[n];if(o===void 0)throw new TypeError(`Artifact JSON property ${n} is undefined`);r[n]=V(o,t)}return t.delete(e),r}function y(e,t={}){for(let r of e){let n=r.codePointAt(0);if(n===127)return!0;if(!(n>31)&&!(n===9&&t.allowTab===!0)&&!((n===10||n===13)&&t.allowLineBreaks===!0))return!0}return!1}function ge(e){let t={...j(e),schemaVersion:1,kind:"xeno-hosted-environment"};return{...t,checksum:{algorithm:"sha256",value:I(t)}}}function k(e){let t=[];if(e?.schemaVersion!==1||e.kind!=="xeno-hosted-environment")return t.push("Unsupported hosted environment manifest"),{valid:!1,errors:t};let r;try{let{checksum:n,schemaVersion:o,kind:s,...i}=e;r={...j(i),schemaVersion:1,kind:"xeno-hosted-environment"}}catch(n){return t.push(n instanceof Error?n.message:String(n)),{valid:!1,errors:t}}return u(r)!==u(He(e))&&t.push("Hosted environment manifest is not normalized"),(e.checksum?.algorithm!=="sha256"||e.checksum.value!==I(r))&&t.push("Hosted environment checksum mismatch"),{valid:t.length===0,errors:t}}function he(e){let t=p(e.streamId,"streamId"),r=F(e.sequence,"sequence");if(e.previous){if(e.previous.streamId!==t)throw new Error("Previous event belongs to another stream");if(e.previous.sequence+1!==r)throw new Error("Hosted event sequence must be contiguous")}else if(r!==1)throw new Error("The first hosted event sequence must be 1");let n={schemaVersion:1,kind:"xeno-hosted-event",eventId:p(e.eventId??`hevt_${(0,w.randomUUID)()}`,"eventId"),streamId:t,sequence:r,timestamp:W(e.timestamp??new Date().toISOString(),"timestamp"),type:K(e.type,"type"),actorId:p(e.actorId,"actorId"),...e.idempotencyKey?{idempotencyKey:c(e.idempotencyKey,"idempotencyKey",512)}:{},payload:ve(e.payload??{},"payload"),previousHash:e.previous?.hash??null};return{...n,hash:I(n)}}function ye(e,t){let r=[],n,o=t?t.afterSequence+1:1,s=t?.lastHash??null;for(let a of e){if(a.schemaVersion!==1||a.kind!=="xeno-hosted-event"){r.push(`Unsupported hosted event at sequence ${String(a.sequence)}`);continue}a.sequence!==o&&r.push(`Hosted event sequence gap at ${a.sequence}; expected ${o}`),a.previousHash!==s&&r.push(`Hosted event previous hash mismatch at ${a.sequence}`);let{hash:m,...h}=a;m!==I(h)&&r.push(`Hosted event hash mismatch at ${a.sequence}`),n&&n.streamId!==a.streamId&&r.push(`Hosted event stream changed at ${a.sequence}`),n=a,o=a.sequence+1,s=a.hash}let i=e.at(-1);return{valid:r.length===0,errors:r,cursor:i?{streamId:i.streamId,afterSequence:i.sequence,lastHash:i.hash}:t??null}}function we(e){let t=k(e);if(!t.valid)throw new Error(t.errors.join("; "));return`${e.environmentId}@${e.revision}:${e.checksum.value}`}function Ee(...e){if(e.length===0)throw new Error("At least one idempotency-key part is required");let t=e.map((r,n)=>xe(r,`parts[${n}]`));return`xeno:${(0,w.createHash)("sha256").update(t.join("\0")).digest("hex")}`}function j(e){let t=e.secrets.map((o,s)=>({ref:p(o.ref,`secrets[${s}].ref`),target:o.target.kind==="environment"?{kind:"environment",name:Xe(o.target.name)}:{kind:"file",path:X(o.target.path,`secrets[${s}].target.path`)},required:!!o.required,exposeToChildProcesses:!!o.exposeToChildProcesses})),r=new Set,n=new Set;for(let o of t){if(r.has(o.ref))throw new Error(`Duplicate secret ref: ${o.ref}`);r.add(o.ref);let s=`${o.target.kind}:${o.target.kind==="environment"?o.target.name:o.target.path}`;if(n.has(s))throw new Error(`Duplicate secret target: ${s}`);n.add(s)}if(e.network.default!=="deny")throw new Error("Hosted network policy must be default-deny");return{environmentId:p(e.environmentId,"environmentId"),revision:F(e.revision,"revision"),createdAt:W(e.createdAt,"createdAt"),createdBy:p(e.createdBy,"createdBy"),workspaceId:p(e.workspaceId,"workspaceId"),name:c(e.name,"name",160),repository:{provider:e.repository.provider,repository:c(e.repository.repository,"repository.repository",2048),ref:c(e.repository.ref,"repository.ref",512),...e.repository.commit?{commit:Ie(e.repository.commit,"repository.commit")}:{},...e.repository.subdirectory?{subdirectory:X(e.repository.subdirectory,"repository.subdirectory")}:{},...e.repository.shallow!==void 0?{shallow:!!e.repository.shallow}:{}},image:{reference:c(e.image.reference,"image.reference",2048),digest:ke(e.image.digest),os:e.image.os,architecture:e.image.architecture},setup:e.setup.map((o,s)=>({id:p(o.id,`setup[${s}].id`),command:c(o.command,`setup[${s}].command`,32768),...o.workingDirectory?{workingDirectory:X(o.workingDirectory,`setup[${s}].workingDirectory`)}:{},timeoutMs:d(o.timeoutMs,`setup[${s}].timeoutMs`,1e3,36e5),network:o.network})),caches:e.caches.map((o,s)=>({key:c(o.key,`caches[${s}].key`,512),path:X(o.path,`caches[${s}].path`),...o.restoreKeys?.length?{restoreKeys:Se(o.restoreKeys,`caches[${s}].restoreKeys`,512)}:{},...o.readOnly!==void 0?{readOnly:!!o.readOnly}:{},...o.maxBytes!==void 0?{maxBytes:d(o.maxBytes,`caches[${s}].maxBytes`,1,Number.MAX_SAFE_INTEGER)}:{}})),network:{default:"deny",dns:e.network.dns,destinations:e.network.destinations.map((o,s)=>({host:be(o.host,`network.destinations[${s}].host`),...o.ports?.length?{ports:[...new Set(o.ports.map(i=>d(i,"port",1,65535)))].sort((i,a)=>i-a)}:{},...o.protocols?.length?{protocols:[...new Set(o.protocols)].sort()}:{},reason:c(o.reason,`network.destinations[${s}].reason`,500)})).sort((o,s)=>o.host.localeCompare(s.host)),...e.network.maxResponseBytes!==void 0?{maxResponseBytes:d(e.network.maxResponseBytes,"network.maxResponseBytes",1,Number.MAX_SAFE_INTEGER)}:{}},secrets:t,resources:{cpuMillis:d(e.resources.cpuMillis,"resources.cpuMillis",10,1e6),memoryBytes:d(e.resources.memoryBytes,"resources.memoryBytes",16*1024*1024,Number.MAX_SAFE_INTEGER),diskBytes:d(e.resources.diskBytes,"resources.diskBytes",16*1024*1024,Number.MAX_SAFE_INTEGER),processLimit:d(e.resources.processLimit,"resources.processLimit",1,65535),wallTimeMs:d(e.resources.wallTimeMs,"resources.wallTimeMs",1e3,10080*60*1e3)},retention:{workspaceTtlMs:d(e.retention.workspaceTtlMs,"retention.workspaceTtlMs",0,365*24*60*60*1e3),eventTtlMs:d(e.retention.eventTtlMs,"retention.eventTtlMs",6e4,365*24*60*60*1e3),artifactTtlMs:d(e.retention.artifactTtlMs,"retention.artifactTtlMs",6e4,365*24*60*60*1e3),wipeWorkspace:!!e.retention.wipeWorkspace},labels:Object.fromEntries(Object.entries(e.labels).map(([o,s])=>[K(o,"label key"),c(s,`labels.${o}`,500)]).sort(([o],[s])=>o.localeCompare(s)))}}function He(e){let{checksum:t,...r}=e;return r}function I(e){return(0,w.createHash)("sha256").update(u(e)).digest("hex")}function ve(e,t){let r=u(e);if(Buffer.byteLength(r,"utf8")>256*1024)throw new Error(`${t} exceeds 262144 bytes`);return JSON.parse(r)}function p(e,t){let r=c(e,t,512);if(!/^[A-Za-z0-9][A-Za-z0-9._:@/-]*$/.test(r))throw new Error(`${t} is invalid`);return r}function K(e,t){let r=c(e,t,160);if(!/^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(r))throw new Error(`${t} is invalid`);return r}function c(e,t,r){let n=e.trim();if(!n||n.length>r||y(n,{allowTab:!0,allowLineBreaks:!0}))throw new Error(`${t} is invalid`);return n}function xe(e,t){let r=e.trim();if(r.length>4096||y(r,{allowTab:!0,allowLineBreaks:!0}))throw new Error(`${t} is invalid`);return r}function F(e,t){return d(e,t,1,Number.MAX_SAFE_INTEGER)}function d(e,t,r,n){if(!Number.isSafeInteger(e)||e<r||e>n)throw new Error(`${t} must be an integer between ${r} and ${n}`);return e}function W(e,t){let r=Date.parse(e);if(!Number.isFinite(r)||new Date(r).toISOString()!==e)throw new Error(`${t} must be an ISO-8601 UTC timestamp`);return e}function be(e,t){let r=c(e.toLowerCase(),t,253);if(r==="localhost"||/^(?:\d{1,3}\.){3}\d{1,3}$/.test(r)||r.includes(":")||!/^(?:\*\.)?(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(r))throw new Error(`${t} must be a public DNS hostname or wildcard hostname`);return r}function X(e,t){let r=c(e.replaceAll("\\","/"),t,4096);if(r.startsWith("/")||/^[A-Za-z]:\//.test(r)||r.split("/").includes(".."))throw new Error(`${t} must be workspace-relative`);return r.replace(/^\.\//,"")}function Xe(e){let t=c(e,"secret environment name",256);if(!/^[A-Z_][A-Z0-9_]*$/.test(t))throw new Error("Secret environment target must be an uppercase environment variable name");return t}function ke(e){let t=e.trim().toLowerCase();if(!/^sha256:[a-f0-9]{64}$/.test(t))throw new Error("image.digest must be a sha256 OCI digest");return t}function Ie(e,t){return c(e,t,512)}function Se(e,t,r){return[...new Set(e.map((n,o)=>c(n,`${t}[${o}]`,r)))]}var f=require("node:crypto");function Re(e){let t=typeof e.body=="string"?Buffer.from(e.body,"utf8"):Buffer.from(e.body),r=(0,f.createHash)("sha256").update(t).digest("hex"),n=e.signature?.trim();if(!n)return{valid:!1,source:e.source,bodySha256:r,error:"missing-signature"};if(!e.secret||e.secret.length<16)throw new Error("Webhook secret must contain at least 16 characters");let o,s=n;if(e.source==="slack"){if(!e.timestamp||!/^\d+$/.test(e.timestamp))return{valid:!1,source:e.source,bodySha256:r,error:"invalid-timestamp"};let a=Number(e.timestamp)*1e3,m=Math.abs((e.now??new Date).getTime()-a);if(!Number.isFinite(a)||m>(e.maxClockSkewMs??5*6e4))return{valid:!1,source:e.source,bodySha256:r,timestamp:e.timestamp,error:"stale-timestamp"};o=`v0=${(0,f.createHmac)("sha256",e.secret).update(`v0:${e.timestamp}:`).update(t).digest("hex")}`}else e.source==="gitlab"?o=e.secret:e.source==="teams"?o=`HMAC ${(0,f.createHmac)("sha256",Buffer.from(e.secret,"base64")).update(t).digest("base64")}`:(o=`${e.source==="github"||e.source==="jira"?"sha256=":e.source==="xeno"?"v1=":""}${(0,f.createHmac)("sha256",e.secret).update(t).digest("hex")}`,e.source==="linear"&&s.startsWith("sha256=")&&(s=s.slice(7)));let i=_e(o,s);return{valid:i,source:e.source,bodySha256:r,...e.timestamp?{timestamp:e.timestamp}:{},...i?{}:{error:"invalid-signature"}}}function _e(e,t){let r=Buffer.from(e,"utf8"),n=Buffer.from(t,"utf8");return r.length===n.length&&(0,f.timingSafeEqual)(r,n)}var A=require("node:crypto");var E="xeno.hosted-execution-adapter-certification.v2",$=2,Z=744*60*60*1e3;function Ae(e){return G(e),Buffer.from(M(e),"utf8")}function Te(e,t){if(e?.schemaVersion!==E)throw new Error(`Hosted execution adapter certificate must use ${E}`);let{signature:r,...n}=e;if(G(n),r?.algorithm!=="ed25519")throw new Error("Hosted execution adapter signature must use ed25519");let o=R(t.executableSha256,"executableSha256"),s=R(t.controlPlaneCandidateSha256,"controlPlaneCandidateSha256");if(n.adapter.executableSha256!==o)throw new Error("Hosted execution adapter executable does not match its signed certificate");if(n.controlPlaneCandidateSha256!==s)throw new Error("Hosted execution adapter certificate is bound to another control-plane candidate");let i=t.platform??process.platform,a=t.architecture??process.arch;if(n.platform.os!==i||n.platform.architecture!==a)throw new Error(`Hosted execution adapter certificate targets ${n.platform.os}-${n.platform.architecture}, not ${i}-${a}`);let m=_(n.issuedAt,"issuedAt"),h=_(n.expiresAt,"expiresAt"),L=(t.now??new Date).getTime();if(m>L+5*6e4)throw new Error("Hosted execution adapter certificate is not yet valid");if(h<=L)throw new Error("Hosted execution adapter certificate has expired");if(h<=m||h-m>Z)throw new Error("Hosted execution adapter certificate lifetime must be positive and at most 31 days");let U=t.trustedKeys[n.reviewer.keyId];if(!U)throw new Error(`Hosted execution adapter reviewer key is not trusted: ${n.reviewer.keyId}`);if(!(0,A.verify)(null,Buffer.from(M(n),"utf8"),U,Oe(r.value,"signature.value")))throw new Error("Hosted execution adapter certificate signature is invalid");return{certificationId:n.certificationId,adapterName:n.adapter.name,adapterVersion:n.adapter.version,protocolVersion:n.adapter.protocolVersion,executableSha256:o,controlPlaneCandidateSha256:s,certificateSha256:(0,A.createHash)("sha256").update(M(e)).digest("hex"),expiresAt:n.expiresAt,reviewerKeyId:n.reviewer.keyId}}function G(e){if(e.schemaVersion!==E)throw new Error(`Hosted execution adapter certificate must use ${E}`);if(S(e.certificationId,"certificationId"),S(e.adapter?.name,"adapter.name"),S(e.adapter?.version,"adapter.version"),e.adapter?.protocolVersion!==$)throw new Error(`Hosted execution adapter protocol must be ${$}`);R(e.adapter.executableSha256,"adapter.executableSha256"),R(e.controlPlaneCandidateSha256,"controlPlaneCandidateSha256"),S(e.reviewer?.keyId,"reviewer.keyId");let t=["immutableImages","filesystemIsolation","networkDefaultDeny","destinationAllowlist","secretProjection","nonRootExecution","readOnlyRoot","processTreeCleanup","resourceLimits","interactiveControl","artifactProtocol","gitResultReporting"];if(!e.capabilities||t.some(r=>e.capabilities[r]!==!0))throw new Error("Hosted execution adapter certificate does not attest every required containment capability");_(e.issuedAt,"issuedAt"),_(e.expiresAt,"expiresAt")}function M(e){return u(e)}function R(e,t){let r=e?.trim().toLowerCase();if(!/^[a-f0-9]{64}$/.test(r))throw new Error(`${t} must be a lowercase SHA-256 digest`);return r}function S(e,t){let r=e?.trim();if(!r||r.length>256||!/^[A-Za-z0-9][A-Za-z0-9._:@/-]*$/.test(r))throw new Error(`${t} is invalid`);return r}function _(e,t){let r=Date.parse(e);if(!Number.isFinite(r)||new Date(r).toISOString()!==e)throw new Error(`${t} must be an ISO-8601 UTC timestamp`);return r}function Oe(e,t){if(typeof e!="string"||e.length===0||e.length>4096||!/^[A-Za-z0-9+/]+={0,2}$/.test(e))throw new Error(`${t} must be bounded base64`);let r=Buffer.from(e,"base64");if(r.toString("base64")!==e)throw new Error(`${t} is not canonical base64`);return r}var Y=require("node:crypto");var ee=2,te=["Read","Write","Edit","Glob","Grep","WebFetch"],Ce=new Set(te);function re(e){if(!oe(e.certificationId))throw new Error("certificationId is invalid");let t=new Set(e.authority.secretRefs);return{certificationId:e.certificationId,environmentChecksum:e.environment.checksum.value,imageDigest:e.environment.image.digest,networkPolicySha256:Q({authority:e.authority.network,policy:e.environment.network}),secretProjectionSha256:Q(e.environment.secrets.filter(r=>t.has(r.ref))),filesystem:e.authority.filesystem,network:e.authority.network==="deny"?"deny":"allowlist",immutableImage:!0,readOnlyRoot:!0,nonRoot:!0,processTreeCleanup:!0,resourceLimits:!0,inferenceGateway:"brokered"}}function ne(e){let t=[];if(!qe(e))return{valid:!1,errors:["Hosted execution job must be an object"]};let r=e;if(r.protocolVersion!==ee||r.kind!=="xeno-hosted-execution-job")return t.push("Unsupported hosted execution protocol"),{valid:!1,errors:t};H(r.runId,"runId",t),H(r.userId,"userId",t),H(r.workspaceId,"workspaceId",t),P(r.workspaceHostPath,"workspaceHostPath",4096,t),P(r.prompt,"prompt",512*1024,t),P(r.model,"model",512,t),r.effort!==void 0&&!["low","medium","high","xhigh","max"].includes(r.effort)&&t.push("effort is invalid"),["default","plan","acceptEdits","auto","dontAsk","bypassPermissions"].includes(r.permissionMode)||t.push("permissionMode is invalid"),(typeof r.runScopedToken!="string"||!r.runScopedToken.startsWith("xrun_")||r.runScopedToken.length>16*1024)&&t.push("runScopedToken is not a bounded run-scoped token");let n;try{n=new URL(r.inferenceBaseUrl),(n.protocol!=="https:"||n.username||n.password||n.hash)&&t.push("inferenceBaseUrl must be credential-free HTTPS")}catch{t.push("inferenceBaseUrl is invalid")}let o=k(r.environment);t.push(...o.errors.map(i=>`environment: ${i}`)),r.environment?.workspaceId!==r.workspaceId&&t.push("environment workspace does not match the job"),r.environment?.image?.os!=="linux"&&t.push("hosted execution image must target Linux");let s=r.environment?.repository?.commit;(typeof s!="string"||!/^(?:[a-fA-F0-9]{40}|[a-fA-F0-9]{64})$/.test(s))&&t.push("environment repository requires a full 40- or 64-character commit object id"),Ve(r.authority,t),$e(r.budget,r.environment,t),Me(r.allowedTools,t),Pe(r,t),De(r,t),n&&!r.environment?.network?.destinations?.some(i=>{let a=i.ports?.length?i.ports:[443];return i.host.toLowerCase()===n.hostname.toLowerCase()&&a.includes(Number(n.port||443))})&&t.push("inference origin is absent from the environment network allowlist");try{let i=Be(r.environment?.repository);r.environment?.network?.destinations?.some(a=>{let m=a.ports?.length?a.ports:[443];return a.host.toLowerCase()===i.hostname&&m.includes(i.port)})||t.push("repository origin is absent from the environment network allowlist")}catch{t.push("environment repository must resolve to a credential-free HTTPS origin")}return{valid:t.length===0,errors:t}}function Ne(e){let t=ne(e);if(!t.valid)throw new Error(`Invalid hosted execution job: ${t.errors.join("; ")}`)}function Ve(e,t){(!e||!["read","workspace-write"].includes(e.filesystem))&&t.push("authority.filesystem is invalid"),(!e||!["deny","environment-policy"].includes(e.network))&&t.push("authority.network is invalid"),(!e||!["deny","approval-required"].includes(e.externalActions))&&t.push("authority.externalActions is invalid"),!Array.isArray(e?.secretRefs)||new Set(e.secretRefs).size!==e.secretRefs.length?t.push("authority.secretRefs must be a unique array"):e.secretRefs.forEach((r,n)=>H(r,`authority.secretRefs[${n}]`,t))}function $e(e,t,r){(!e||!Number.isFinite(e.maxCredits)||e.maxCredits<=0)&&r.push("budget.maxCredits is invalid"),(!e||!D(e.maxDurationMs)||e.maxDurationMs>(t?.resources?.wallTimeMs??0))&&r.push("budget.maxDurationMs is invalid or exceeds the environment limit"),e?.maxTokens!==void 0&&!D(e.maxTokens)&&r.push("budget.maxTokens is invalid"),e?.maxToolCalls!==void 0&&!D(e.maxToolCalls)&&r.push("budget.maxToolCalls is invalid")}function Me(e,t){if(!Array.isArray(e)||e.length<1||e.length>512||new Set(e).size!==e.length){t.push("allowedTools must contain 1..512 unique tool names");return}e.forEach((r,n)=>{H(r,`allowedTools[${n}]`,t),Ce.has(r)||t.push(`allowedTools[${n}] is not in the hosted v0.1 registry`)})}function Pe(e,t){if(!Array.isArray(e.secrets)||e.secrets.length>128){t.push("secrets must be a bounded array");return}let r=new Set(e.authority?.secretRefs??[]),n=new Map((e.environment?.secrets??[]).map(s=>[s.ref,s])),o=new Set;for(let[s,i]of e.secrets.entries()){let a=n.get(i.ref);if(!a||!r.has(i.ref)||o.has(i.ref)){t.push(`secrets[${s}] is undeclared, unauthorized, or duplicated`);continue}o.add(i.ref),(v(a.target)!==v(i.target)||a.exposeToChildProcesses!==i.exposeToChildProcesses)&&t.push(`secrets[${s}] does not match its declared projection`),(typeof i.value!="string"||i.value.length<1||Buffer.byteLength(i.value,"utf8")>1024*1024)&&t.push(`secrets[${s}] value is empty or too large`)}for(let s of e.environment?.secrets??[])s.required&&(!r.has(s.ref)||!o.has(s.ref))&&t.push(`required secret ${s.ref} is absent or unauthorized`);[...r].some(s=>!n.has(s))&&t.push("authority references an undeclared secret")}function De(e,t){let r=e.expectedBoundary;if(!r){t.push("expectedBoundary is missing");return}let n;try{n=re({certificationId:r.certificationId,environment:e.environment,authority:e.authority})}catch{t.push("expectedBoundary does not match the hosted execution contract");return}(!oe(r.certificationId)||v(r)!==v(n))&&t.push("expectedBoundary does not match the hosted execution contract")}function H(e,t,r){(typeof e!="string"||!/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,511}$/.test(e))&&r.push(`${t} is invalid`)}function P(e,t,r,n){(typeof e!="string"||e.length<1||e.length>r||e.includes("\0"))&&n.push(`${t} is invalid`)}function D(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function oe(e){return typeof e=="string"&&/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,511}$/.test(e)}function qe(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function v(e){return u(e)}function Q(e){return(0,Y.createHash)("sha256").update(v(e)).digest("hex")}function Be(e){if(!e)throw new Error("repository source is missing");let t=e.repository.replace(/^\/+|\/+$/g,""),r=e.provider==="github"&&!t.includes("://")?`https://github.com/${t}.git`:e.provider==="gitlab"&&!t.includes("://")?`https://gitlab.com/${t}.git`:e.provider==="bitbucket"&&!t.includes("://")?`https://bitbucket.org/${t}.git`:e.repository,n=new URL(r);if(n.protocol!=="https:"||n.username||n.password||n.hash)throw new Error("repository origin is not credential-free HTTPS");return{hostname:n.hostname.toLowerCase(),port:Number(n.port||443)}}var O=require("node:crypto");var B=1,J=1;function ie(e){let t={schemaVersion:B,kind:"xeno-hosted-control",controlId:l(e.controlId??`hctl_${(0,O.randomUUID)()}`,"controlId"),runId:l(e.runId,"runId"),workspaceId:l(e.workspaceId,"workspaceId"),actorId:l(e.actorId,"actorId"),idempotencyKey:g(e.idempotencyKey,"idempotencyKey",512),createdAt:z(e.createdAt,"createdAt"),action:Ue(e.action)};return{...t,hash:{algorithm:"sha256",value:ce(t)}}}function Je(e){let t=[];try{let{hash:r,schemaVersion:n,kind:o,...s}=e,i=ie(s);(e.schemaVersion!==B||e.kind!=="xeno-hosted-control")&&t.push("Unsupported hosted control command"),x(T(e))!==x(T(i))&&t.push("Hosted control command is not normalized"),(r?.algorithm!=="sha256"||r.value!==i.hash.value)&&t.push("Hosted control command hash mismatch")}catch(r){t.push(r instanceof Error?r.message:String(r))}return{valid:t.length===0,errors:t}}function ze(e){if(!["accepted","applied","rejected","unsupported"].includes(e.status))throw new Error("Hosted control acknowledgement status is invalid");return{controlId:l(e.controlId,"controlId"),status:e.status,acknowledgedAt:z(e.acknowledgedAt,"acknowledgedAt"),...e.reason?{reason:g(e.reason,"reason",2048)}:{}}}function ae(e){let t=e.git?{...e.git.branch?{branch:q(e.git.branch,"git.branch")}:{},...e.git.baseRef?{baseRef:q(e.git.baseRef,"git.baseRef")}:{},...e.git.commit?{commit:q(e.git.commit,"git.commit")}:{}}:void 0,r={schemaVersion:J,kind:"xeno-hosted-run-result",runId:l(e.runId,"runId"),workspaceId:l(e.workspaceId,"workspaceId"),completedAt:z(e.completedAt,"completedAt"),...t&&Object.keys(t).length>0?{git:t}:{},...e.pullRequest?{pullRequest:je(e.pullRequest)}:{},artifactIds:se(e.artifactIds,"artifactIds"),evidenceArtifactIds:se(e.evidenceArtifactIds,"evidenceArtifactIds")};return{...r,hash:{algorithm:"sha256",value:ce(r)}}}function Le(e){let t=[];try{let{hash:r,schemaVersion:n,kind:o,...s}=e,i=ae(s);(e.schemaVersion!==J||e.kind!=="xeno-hosted-run-result")&&t.push("Unsupported hosted run result"),x(T(e))!==x(T(i))&&t.push("Hosted run result is not normalized"),(r?.algorithm!=="sha256"||r.value!==i.hash.value)&&t.push("Hosted run result hash mismatch")}catch(r){t.push(r instanceof Error?r.message:String(r))}return{valid:t.length===0,errors:t}}function Ue(e){if(e?.type==="message")return{type:"message",message:g(e.message,"action.message",32768)};if(e?.type==="approval"){if(e.decision!=="approved"&&e.decision!=="rejected")throw new Error("Hosted approval decision is invalid");return{type:"approval",requestId:l(e.requestId,"action.requestId"),decision:e.decision,scopeHash:Ke(e.scopeHash,"action.scopeHash"),...e.rationale?{rationale:g(e.rationale,"action.rationale",4096)}:{}}}throw new Error("Hosted control action is invalid")}function je(e){let t;try{t=new URL(e.url)}catch{throw new Error("pullRequest.url is invalid")}if(t.protocol!=="https:"||t.username||t.password)throw new Error("pullRequest.url must be credential-free HTTPS");if(!Number.isSafeInteger(e.number)||e.number<1)throw new Error("pullRequest.number must be a positive integer");return{provider:l(e.provider,"pullRequest.provider"),repository:g(e.repository,"pullRequest.repository",2048),number:e.number,url:t.toString()}}function se(e,t){if(!Array.isArray(e)||e.length>1e4)throw new Error(`${t} is invalid`);return[...new Set(e.map((r,n)=>l(r,`${t}[${n}]`)))].sort()}function q(e,t){return g(e,t,512)}function l(e,t){let r=g(e,t,512);if(!/^[A-Za-z0-9][A-Za-z0-9._:@/-]*$/.test(r))throw new Error(`${t} is invalid`);return r}function g(e,t,r){let n=e?.trim();if(!n||n.length>r||y(n,{allowTab:!0,allowLineBreaks:!0}))throw new Error(`${t} is invalid`);return n}function z(e,t){let r=Date.parse(e);if(!Number.isFinite(r)||new Date(r).toISOString()!==e)throw new Error(`${t} must be ISO-8601 UTC`);return e}function Ke(e,t){let r=e?.trim().toLowerCase();if(!/^[a-f0-9]{64}$/.test(r))throw new Error(`${t} must be a lowercase SHA-256 digest`);return r}function ce(e){return(0,O.createHash)("sha256").update(x(e)).digest("hex")}function x(e){return u(e)}function T(e){let{hash:t,...r}=e;return r}0&&(module.exports={XENO_HOSTED_CONTROL_SCHEMA_VERSION,XENO_HOSTED_ENVIRONMENT_SCHEMA_VERSION,XENO_HOSTED_EVENT_SCHEMA_VERSION,XENO_HOSTED_EXECUTION_ADAPTER_CERTIFICATION_SCHEMA,XENO_HOSTED_EXECUTION_ADAPTER_MAX_CERTIFICATE_LIFETIME_MS,XENO_HOSTED_EXECUTION_ADAPTER_PROTOCOL_VERSION,XENO_HOSTED_EXECUTION_PROTOCOL_VERSION,XENO_HOSTED_EXECUTION_TOOL_NAMES,XENO_HOSTED_RESULT_SCHEMA_VERSION,XENO_HOSTED_RUN_SCHEMA_VERSION,XENO_HOSTED_TRIGGER_SCHEMA_VERSION,assertValidXenoHostedExecutionJob,createXenoHostedControlCommand,createXenoHostedEnvironmentManifest,createXenoHostedEvent,createXenoHostedExecutionBoundaryReceipt,createXenoHostedRunResult,deriveHostedIdempotencyKey,hostedEnvironmentIdentity,normalizeXenoHostedControlAcknowledgement,verifyXenoHostedControlCommand,verifyXenoHostedEnvironmentManifest,verifyXenoHostedEventChain,verifyXenoHostedExecutionAdapterCertification,verifyXenoHostedExecutionJob,verifyXenoHostedRunResult,verifyXenoHostedWebhook,xenoHostedExecutionAdapterSigningPayload});