@shumkov/orchestra 0.10.19 → 0.10.21

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.
@@ -90,10 +90,86 @@ const FORBIDDEN_REQUEST_FIELDS = new Set([
90
90
  'permissionProfile',
91
91
  'config',
92
92
  ]);
93
+ // Hook trust is content-addressed and reported only by the app server, so the
94
+ // verifier compares a whole inventory against a manifest fixed at construction
95
+ // rather than harvesting values entry by entry.
96
+ const HOOK_EVENT_NAMES = Object.freeze([
97
+ 'preToolUse',
98
+ 'permissionRequest',
99
+ 'postToolUse',
100
+ 'preCompact',
101
+ 'postCompact',
102
+ 'sessionStart',
103
+ 'sessionEnd',
104
+ 'userPromptSubmit',
105
+ 'subagentStart',
106
+ 'subagentStop',
107
+ 'stop',
108
+ ]);
109
+ const HOOK_TRUST_STATUSES = Object.freeze([
110
+ 'managed',
111
+ 'untrusted',
112
+ 'trusted',
113
+ 'modified',
114
+ ]);
115
+ const HOOK_PHASES = Object.freeze({
116
+ discovery: 'untrusted',
117
+ trusted: 'trusted',
118
+ });
119
+ const HOOK_METADATA_REQUIRED_FIELDS = Object.freeze([
120
+ 'currentHash',
121
+ 'displayOrder',
122
+ 'enabled',
123
+ 'eventName',
124
+ 'handlerType',
125
+ 'isManaged',
126
+ 'key',
127
+ 'source',
128
+ 'sourcePath',
129
+ 'timeoutSec',
130
+ 'trustStatus',
131
+ ]);
132
+ // All five are reported on every entry; four of them always null. A missing or
133
+ // populated one means the reported shape is not the shape this pin was built
134
+ // against, which is a refusal rather than something to interpret.
135
+ const HOOK_METADATA_NULL_OPTIONAL_FIELDS = Object.freeze([
136
+ 'additionalContextLimit',
137
+ 'matcher',
138
+ 'pluginId',
139
+ 'statusMessage',
140
+ ]);
141
+ const HOOK_METADATA_FIELDS = Object.freeze([
142
+ ...HOOK_METADATA_REQUIRED_FIELDS,
143
+ ...HOOK_METADATA_NULL_OPTIONAL_FIELDS,
144
+ 'command',
145
+ ]);
146
+ const HOOK_DESCRIPTOR_FIELDS = Object.freeze([
147
+ 'ordinal',
148
+ 'configKey',
149
+ 'sourcePath',
150
+ 'event',
151
+ 'handlerType',
152
+ 'source',
153
+ 'isManaged',
154
+ 'displayOrder',
155
+ 'timeoutSec',
156
+ 'commandSha256',
157
+ ]);
158
+ const HOOK_INVENTORY_ENTRY_FIELDS = Object.freeze([
159
+ 'cwd',
160
+ 'errors',
161
+ 'warnings',
162
+ 'hooks',
163
+ ]);
164
+ const MAX_HOOK_DESCRIPTORS = 16;
165
+ const HOOK_CURRENT_HASH_PATTERN = /^sha256:[a-f0-9]{64}$/;
166
+ const SHA256_HEX_PATTERN = /^[a-f0-9]{64}$/;
167
+
93
168
  const CONSTRUCTOR_KEYS = new Set([
94
169
  'binary',
95
170
  'cwd',
96
171
  'codexHome',
172
+ 'hookManifest',
97
173
  'env',
98
174
  'spawnFn',
99
175
  'killFn',
@@ -120,6 +196,9 @@ const CONSTRUCTOR_KEYS = new Set([
120
196
  'maxQueuedBytes',
121
197
  ]);
122
198
 
199
+ // Keyed by the pending record itself, so a forged record inserted into the
200
+ // pending map carries no projector and can never yield a raw response.
201
+ const RESULT_PROJECTORS = new WeakMap();
123
202
  const CLIENT_REQUESTS = new Map(Object.entries(protocolSchema.clientRequests));
124
203
  const CLIENT_NOTIFICATIONS = new Set(protocolSchema.clientNotifications);
125
204
  const DENIED_CLIENT_REQUESTS = new Set(protocolSchema.deniedClientRequests);
@@ -1748,6 +1827,193 @@ function projectTextInput(input) {
1748
1827
  });
1749
1828
  }
1750
1829
 
1830
+ function hookEventToken(event) {
1831
+ return event.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
1832
+ }
1833
+
1834
+ // The config key Codex reports for a hook is derived from the file that
1835
+ // declares it and the event it is registered on; the trailing pair is the
1836
+ // entry's position within that event, which this pin fixes at the first slot.
1837
+ function hookConfigKeyFor(sourcePath, event) {
1838
+ return `${sourcePath}:${hookEventToken(event)}:0:0`;
1839
+ }
1840
+
1841
+ function hookManifestType(message) {
1842
+ return new TypeError(`CodexAppServerClient: ${message}`);
1843
+ }
1844
+
1845
+ function normalizeHookManifest(value) {
1846
+ if (value == null) return null;
1847
+ if (
1848
+ !value
1849
+ || typeof value !== 'object'
1850
+ || Array.isArray(value)
1851
+ || JSON.stringify(Object.keys(value).sort())
1852
+ !== JSON.stringify(['entries', 'ownedCwd'])
1853
+ ) {
1854
+ throw hookManifestType('hookManifest must be {ownedCwd, entries}');
1855
+ }
1856
+ const { ownedCwd, entries } = value;
1857
+ if (typeof ownedCwd !== 'string' || !path.isAbsolute(ownedCwd)) {
1858
+ throw hookManifestType('hookManifest ownedCwd must be an absolute path');
1859
+ }
1860
+ if (
1861
+ !Array.isArray(entries)
1862
+ || entries.length < 1
1863
+ || entries.length > MAX_HOOK_DESCRIPTORS
1864
+ ) {
1865
+ throw hookManifestType(
1866
+ `hookManifest requires 1..${MAX_HOOK_DESCRIPTORS} descriptors`,
1867
+ );
1868
+ }
1869
+ const events = new Set();
1870
+ const normalized = entries.map((entry, index) => {
1871
+ if (
1872
+ !entry
1873
+ || typeof entry !== 'object'
1874
+ || Array.isArray(entry)
1875
+ || JSON.stringify(Object.keys(entry).sort())
1876
+ !== JSON.stringify([...HOOK_DESCRIPTOR_FIELDS].sort())
1877
+ ) {
1878
+ throw hookManifestType('hookManifest descriptor shape is unsupported');
1879
+ }
1880
+ // The ordinal is the descriptor's position and the position Codex reports
1881
+ // it in; a manifest that disagrees with itself is refused here rather than
1882
+ // compared against a peer response later.
1883
+ if (entry.ordinal !== index || entry.displayOrder !== index) {
1884
+ throw hookManifestType('hookManifest ordinals must be dense and ordered');
1885
+ }
1886
+ if (
1887
+ typeof entry.sourcePath !== 'string'
1888
+ || !path.isAbsolute(entry.sourcePath)
1889
+ || !HOOK_EVENT_NAMES.includes(entry.event)
1890
+ || entry.handlerType !== 'command'
1891
+ || entry.source !== 'user'
1892
+ || entry.isManaged !== false
1893
+ || !Number.isSafeInteger(entry.timeoutSec)
1894
+ || entry.timeoutSec < 1
1895
+ || typeof entry.commandSha256 !== 'string'
1896
+ || !SHA256_HEX_PATTERN.test(entry.commandSha256)
1897
+ || entry.configKey !== hookConfigKeyFor(entry.sourcePath, entry.event)
1898
+ ) {
1899
+ throw hookManifestType('hookManifest descriptor is outside the pin');
1900
+ }
1901
+ if (events.has(entry.event)) {
1902
+ throw hookManifestType('hookManifest repeats a hook event');
1903
+ }
1904
+ events.add(entry.event);
1905
+ return {
1906
+ ordinal: entry.ordinal,
1907
+ configKey: entry.configKey,
1908
+ sourcePath: entry.sourcePath,
1909
+ event: entry.event,
1910
+ handlerType: entry.handlerType,
1911
+ source: entry.source,
1912
+ isManaged: entry.isManaged,
1913
+ displayOrder: entry.displayOrder,
1914
+ timeoutSec: entry.timeoutSec,
1915
+ commandSha256: entry.commandSha256,
1916
+ };
1917
+ });
1918
+ return deepFreeze({ ownedCwd, entries: normalized });
1919
+ }
1920
+
1921
+ function hookTrustUnverified() {
1922
+ return new CodexAppServerError(
1923
+ 'app-server hook inventory did not match the pinned manifest',
1924
+ 'CODEX_HOOK_TRUST_UNVERIFIED',
1925
+ );
1926
+ }
1927
+
1928
+ function hookEntryMatches(hook, descriptor, expectedTrustStatus) {
1929
+ if (
1930
+ !hook
1931
+ || typeof hook !== 'object'
1932
+ || Array.isArray(hook)
1933
+ || Object.getPrototypeOf(hook) !== Object.prototype
1934
+ || Object.getOwnPropertySymbols(hook).length > 0
1935
+ || JSON.stringify(Object.keys(hook).sort())
1936
+ !== JSON.stringify([...HOOK_METADATA_FIELDS].sort())
1937
+ ) return false;
1938
+ for (const field of HOOK_METADATA_NULL_OPTIONAL_FIELDS) {
1939
+ if (hook[field] !== null) return false;
1940
+ }
1941
+ if (
1942
+ typeof hook.command !== 'string'
1943
+ || createHash('sha256').update(hook.command).digest('hex')
1944
+ !== descriptor.commandSha256
1945
+ ) return false;
1946
+ return (
1947
+ hook.eventName === descriptor.event
1948
+ && hook.key === descriptor.configKey
1949
+ && hook.sourcePath === descriptor.sourcePath
1950
+ && hook.handlerType === descriptor.handlerType
1951
+ && hook.source === descriptor.source
1952
+ && hook.isManaged === descriptor.isManaged
1953
+ && hook.displayOrder === descriptor.displayOrder
1954
+ && hook.timeoutSec === descriptor.timeoutSec
1955
+ && hook.enabled === true
1956
+ && typeof hook.currentHash === 'string'
1957
+ && HOOK_CURRENT_HASH_PATTERN.test(hook.currentHash)
1958
+ && HOOK_TRUST_STATUSES.includes(hook.trustStatus)
1959
+ && hook.trustStatus === expectedTrustStatus
1960
+ );
1961
+ }
1962
+
1963
+ // The whole inventory decides. A per-entry harvest would take a well-typed hash
1964
+ // off a foreign, duplicated or tampered entry, so nothing is projected until
1965
+ // every descriptor has matched its reported hook exactly.
1966
+ function projectHookInventory(value, manifest, phase) {
1967
+ const expectedTrustStatus = HOOK_PHASES[phase];
1968
+ if (
1969
+ !expectedTrustStatus
1970
+ || !value
1971
+ || typeof value !== 'object'
1972
+ || Array.isArray(value)
1973
+ || Object.getPrototypeOf(value) !== Object.prototype
1974
+ || JSON.stringify(Object.keys(value)) !== JSON.stringify(['data'])
1975
+ || !Array.isArray(value.data)
1976
+ || value.data.length !== 1
1977
+ ) throw hookTrustUnverified();
1978
+ const entry = value.data[0];
1979
+ if (
1980
+ !entry
1981
+ || typeof entry !== 'object'
1982
+ || Array.isArray(entry)
1983
+ || Object.getPrototypeOf(entry) !== Object.prototype
1984
+ || JSON.stringify(Object.keys(entry).sort())
1985
+ !== JSON.stringify([...HOOK_INVENTORY_ENTRY_FIELDS].sort())
1986
+ // The response echoes the requested cwd back rather than scoping to it, so
1987
+ // this equality pins the response against malformation, nothing more.
1988
+ || entry.cwd !== manifest.ownedCwd
1989
+ || !Array.isArray(entry.errors)
1990
+ || entry.errors.length !== 0
1991
+ || !Array.isArray(entry.warnings)
1992
+ || entry.warnings.length !== 0
1993
+ || !Array.isArray(entry.hooks)
1994
+ || entry.hooks.length !== manifest.entries.length
1995
+ ) throw hookTrustUnverified();
1996
+ const seenKeys = new Set();
1997
+ const seenEvents = new Set();
1998
+ for (const [index, descriptor] of manifest.entries.entries()) {
1999
+ const hook = entry.hooks[index];
2000
+ if (!hookEntryMatches(hook, descriptor, expectedTrustStatus)) {
2001
+ throw hookTrustUnverified();
2002
+ }
2003
+ if (seenKeys.has(hook.key) || seenEvents.has(hook.eventName)) {
2004
+ throw hookTrustUnverified();
2005
+ }
2006
+ seenKeys.add(hook.key);
2007
+ seenEvents.add(hook.eventName);
2008
+ }
2009
+ return deepFreeze(manifest.entries.map((descriptor, index) => ({
2010
+ ordinal: descriptor.ordinal,
2011
+ currentHash: entry.hooks[index].currentHash,
2012
+ trustStatus: entry.hooks[index].trustStatus,
2013
+ enabled: entry.hooks[index].enabled,
2014
+ })));
2015
+ }
2016
+
1751
2017
  function projectRequestParams(method, params, spec, ownedCwd) {
1752
2018
  if (spec.params === 'omitted') {
1753
2019
  if (params !== undefined) {
@@ -1871,6 +2137,19 @@ function projectRequestParams(method, params, spec, ownedCwd) {
1871
2137
  model: boundedRequiredString(params.model, 'model'),
1872
2138
  };
1873
2139
  }
2140
+ if (method === 'hooks/list') {
2141
+ if (
2142
+ !Array.isArray(params.cwds)
2143
+ || params.cwds.length !== 1
2144
+ || params.cwds[0] !== ownedCwd
2145
+ ) {
2146
+ throw new CodexAppServerError(
2147
+ 'app-server hook listing must target the owned workspace',
2148
+ 'CODEX_RPC_REJECTED',
2149
+ );
2150
+ }
2151
+ return { cwds: [ownedCwd] };
2152
+ }
1874
2153
  if (method === 'thread/resume') return { threadId: threadId() };
1875
2154
  if (method === 'turn/start') {
1876
2155
  const projected = {
@@ -1967,6 +2246,137 @@ function sameOptionalFingerprint(left, right) {
1967
2246
  );
1968
2247
  }
1969
2248
 
2249
+ // Raw dispatch is module-scoped on purpose: it is absent from the supported
2250
+ // public surface, so neither the internal flag nor the result projector can be
2251
+ // forged through an options bag handed to request().
2252
+ function dispatchRequest(client, method, params, {
2253
+ internal = false,
2254
+ projectResult = null,
2255
+ timeoutMs = client.requestTimeoutMs,
2256
+ onWriteAttempted,
2257
+ onResponseObserved,
2258
+ } = {}) {
2259
+ const spec = CLIENT_REQUESTS.get(method);
2260
+ if (
2261
+ !spec
2262
+ || DENIED_CLIENT_REQUESTS.has(method)
2263
+ || (spec.internal && !internal)
2264
+ ) {
2265
+ return Promise.reject(new CodexAppServerError(
2266
+ 'app-server request method is not allowlisted',
2267
+ 'CODEX_RPC_REJECTED',
2268
+ ));
2269
+ }
2270
+ if (client.protocolError) return Promise.reject(client.protocolError);
2271
+ // initialize is the one request that runs before readiness; every other
2272
+ // internal request is held to the same readiness gate as a public one.
2273
+ const requiredState = method === 'initialize' ? 'initializing' : 'ready';
2274
+ if (client.state !== requiredState) {
2275
+ return Promise.reject(new CodexAppServerError(
2276
+ 'app-server client is not ready',
2277
+ 'CODEX_CLIENT_STATE',
2278
+ ));
2279
+ }
2280
+ let projectedParams;
2281
+ try {
2282
+ projectedParams = projectRequestParams(method, params, spec, client.cwd);
2283
+ assertPositiveInteger(timeoutMs, 'request timeout');
2284
+ } catch (error) {
2285
+ return Promise.reject(error);
2286
+ }
2287
+ if (
2288
+ spec.stateChanging
2289
+ && (
2290
+ typeof onWriteAttempted !== 'function'
2291
+ || typeof onResponseObserved !== 'function'
2292
+ )
2293
+ ) {
2294
+ return Promise.reject(new CodexAppServerError(
2295
+ `app-server ${method} requires delivery checkpoints`,
2296
+ 'CODEX_RPC_REJECTED',
2297
+ ));
2298
+ }
2299
+ if (!client._stdinWritable()) {
2300
+ const cause = new CodexAppServerError(
2301
+ 'app-server stdin is not writable',
2302
+ 'CODEX_TRANSPORT_ERROR',
2303
+ );
2304
+ return Promise.reject(
2305
+ spec.stateChanging
2306
+ ? mutationDeliveryError({ method, writeAttempted: false }, cause)
2307
+ : cause,
2308
+ );
2309
+ }
2310
+ if (client.pending.size >= client.maxPendingRequests) {
2311
+ return Promise.reject(new CodexAppServerError(
2312
+ 'app-server pending request limit reached',
2313
+ 'CODEX_RPC_REJECTED',
2314
+ ));
2315
+ }
2316
+ if (client.usedRequestIds.size >= client.maxUsedRequestIds) {
2317
+ const error = new CodexAppServerError(
2318
+ 'app-server request ID space is exhausted for this generation',
2319
+ 'CODEX_REQUEST_ID_EXHAUSTED',
2320
+ );
2321
+ client._fault(error);
2322
+ return Promise.reject(error);
2323
+ }
2324
+
2325
+ let id;
2326
+ try {
2327
+ id = client.requestIdFactory
2328
+ ? client.requestIdFactory(client.nextRequestId)
2329
+ : client.nextRequestId;
2330
+ client.nextRequestId += 1;
2331
+ assertRequestId(id);
2332
+ if (client.usedRequestIds.has(id)) {
2333
+ throw new CodexAppServerError(
2334
+ 'app-server request ID was reused',
2335
+ 'CODEX_PROTOCOL_ERROR',
2336
+ );
2337
+ }
2338
+ client.usedRequestIds.add(id);
2339
+ } catch (error) {
2340
+ return Promise.reject(error);
2341
+ }
2342
+
2343
+ return new Promise((resolve, reject) => {
2344
+ const pending = {
2345
+ id,
2346
+ method,
2347
+ stateChanging: spec.stateChanging,
2348
+ writeAttempted: false,
2349
+ onWriteAttempted,
2350
+ onResponseObserved,
2351
+ resolve,
2352
+ reject,
2353
+ timer: null,
2354
+ sinkController: null,
2355
+ };
2356
+ pending.timer = client.setTimer(() => {
2357
+ if (client.pending.get(id) !== pending) return;
2358
+ const timeoutError = new CodexAppServerError(
2359
+ `app-server ${method} timed out`,
2360
+ 'CODEX_RPC_TIMEOUT',
2361
+ );
2362
+ if (pending.stateChanging && pending.writeAttempted) {
2363
+ client._fault(timeoutError);
2364
+ return;
2365
+ }
2366
+ pending.sinkController?.abort(timeoutError);
2367
+ client.pending.delete(id);
2368
+ reject(
2369
+ pending.stateChanging
2370
+ ? mutationDeliveryError(pending, timeoutError)
2371
+ : timeoutError,
2372
+ );
2373
+ }, timeoutMs);
2374
+ if (projectResult) RESULT_PROJECTORS.set(pending, projectResult);
2375
+ client.pending.set(id, pending);
2376
+ void client._dispatchRequest(pending, projectedParams);
2377
+ });
2378
+ }
2379
+
1970
2380
  class CodexAppServerClient extends EventEmitter {
1971
2381
  constructor(options = {}) {
1972
2382
  super();
@@ -1985,6 +2395,7 @@ class CodexAppServerClient extends EventEmitter {
1985
2395
  setTimer = setTimeout,
1986
2396
  clearTimer = clearTimeout,
1987
2397
  requestIdFactory = null,
2398
+ hookManifest = null,
1988
2399
  onNotification = async () => {},
1989
2400
  onFault,
1990
2401
  attestBinaryFn = attestPinnedCodexBinary,
@@ -2131,6 +2542,14 @@ class CodexAppServerClient extends EventEmitter {
2131
2542
  maxQueuedLines,
2132
2543
  maxQueuedBytes,
2133
2544
  });
2545
+ // Fixed for the client's life: a caller that could pass or replace a
2546
+ // manifest later could narrow what a session claims to have verified.
2547
+ Object.defineProperty(this, 'hookManifest', {
2548
+ value: normalizeHookManifest(hookManifest),
2549
+ writable: false,
2550
+ configurable: false,
2551
+ enumerable: true,
2552
+ });
2134
2553
  this.env = buildCodexAppServerEnv(codexHome, env);
2135
2554
  this.state = 'new';
2136
2555
  this.child = null;
@@ -2302,7 +2721,7 @@ class CodexAppServerClient extends EventEmitter {
2302
2721
  );
2303
2722
  }
2304
2723
  this.state = 'initializing';
2305
- const result = await this._request('initialize', {
2724
+ const result = await dispatchRequest(this, 'initialize', {
2306
2725
  clientInfo: {
2307
2726
  name: 'orchestra',
2308
2727
  title: 'Orchestra',
@@ -2386,136 +2805,36 @@ class CodexAppServerClient extends EventEmitter {
2386
2805
  onWriteAttempted,
2387
2806
  onResponseObserved,
2388
2807
  } = {}) {
2389
- return this._request(method, params, {
2808
+ return dispatchRequest(this, method, params, {
2390
2809
  timeoutMs,
2391
2810
  onWriteAttempted,
2392
2811
  onResponseObserved,
2393
2812
  });
2394
2813
  }
2395
2814
 
2396
- _request(method, params, {
2397
- internal = false,
2398
- timeoutMs = this.requestTimeoutMs,
2399
- onWriteAttempted,
2400
- onResponseObserved,
2401
- } = {}) {
2402
- const spec = CLIENT_REQUESTS.get(method);
2403
- if (
2404
- !spec
2405
- || DENIED_CLIENT_REQUESTS.has(method)
2406
- || (spec.internal && !internal)
2407
- ) {
2408
- return Promise.reject(new CodexAppServerError(
2409
- 'app-server request method is not allowlisted',
2410
- 'CODEX_RPC_REJECTED',
2411
- ));
2412
- }
2413
- if (this.protocolError) return Promise.reject(this.protocolError);
2815
+ // The only supported path to hooks/list. It answers with ordinals, hashes,
2816
+ // statuses and enablement for the manifest it was built with, and nothing
2817
+ // else: the raw inventory is reduced where it is parsed and never reaches
2818
+ // this frame.
2819
+ verifyHooks(options = {}) {
2820
+ const manifest = this.hookManifest;
2414
2821
  if (
2415
- (!internal && this.state !== 'ready')
2416
- || (internal && method === 'initialize' && this.state !== 'initializing')
2822
+ !options
2823
+ || typeof options !== 'object'
2824
+ || Array.isArray(options)
2825
+ || JSON.stringify(Object.keys(options)) !== JSON.stringify(['phase'])
2826
+ || !Object.hasOwn(HOOK_PHASES, options.phase)
2827
+ || !manifest
2417
2828
  ) {
2418
2829
  return Promise.reject(new CodexAppServerError(
2419
- 'app-server client is not ready',
2420
- 'CODEX_CLIENT_STATE',
2830
+ 'app-server hook verification is unavailable for this client',
2831
+ 'CODEX_HOOK_TRUST_UNVERIFIED',
2421
2832
  ));
2422
2833
  }
2423
- let projectedParams;
2424
- try {
2425
- projectedParams = projectRequestParams(method, params, spec, this.cwd);
2426
- assertPositiveInteger(timeoutMs, 'request timeout');
2427
- } catch (error) {
2428
- return Promise.reject(error);
2429
- }
2430
- if (
2431
- spec.stateChanging
2432
- && (
2433
- typeof onWriteAttempted !== 'function'
2434
- || typeof onResponseObserved !== 'function'
2435
- )
2436
- ) {
2437
- return Promise.reject(new CodexAppServerError(
2438
- `app-server ${method} requires delivery checkpoints`,
2439
- 'CODEX_RPC_REJECTED',
2440
- ));
2441
- }
2442
- if (!this._stdinWritable()) {
2443
- const cause = new CodexAppServerError(
2444
- 'app-server stdin is not writable',
2445
- 'CODEX_TRANSPORT_ERROR',
2446
- );
2447
- return Promise.reject(
2448
- spec.stateChanging
2449
- ? mutationDeliveryError({ method, writeAttempted: false }, cause)
2450
- : cause,
2451
- );
2452
- }
2453
- if (this.pending.size >= this.maxPendingRequests) {
2454
- return Promise.reject(new CodexAppServerError(
2455
- 'app-server pending request limit reached',
2456
- 'CODEX_RPC_REJECTED',
2457
- ));
2458
- }
2459
- if (this.usedRequestIds.size >= this.maxUsedRequestIds) {
2460
- const error = new CodexAppServerError(
2461
- 'app-server request ID space is exhausted for this generation',
2462
- 'CODEX_REQUEST_ID_EXHAUSTED',
2463
- );
2464
- this._fault(error);
2465
- return Promise.reject(error);
2466
- }
2467
-
2468
- let id;
2469
- try {
2470
- id = this.requestIdFactory
2471
- ? this.requestIdFactory(this.nextRequestId)
2472
- : this.nextRequestId;
2473
- this.nextRequestId += 1;
2474
- assertRequestId(id);
2475
- if (this.usedRequestIds.has(id)) {
2476
- throw new CodexAppServerError(
2477
- 'app-server request ID was reused',
2478
- 'CODEX_PROTOCOL_ERROR',
2479
- );
2480
- }
2481
- this.usedRequestIds.add(id);
2482
- } catch (error) {
2483
- return Promise.reject(error);
2484
- }
2485
-
2486
- return new Promise((resolve, reject) => {
2487
- const pending = {
2488
- id,
2489
- method,
2490
- stateChanging: spec.stateChanging,
2491
- writeAttempted: false,
2492
- onWriteAttempted,
2493
- onResponseObserved,
2494
- resolve,
2495
- reject,
2496
- timer: null,
2497
- sinkController: null,
2498
- };
2499
- pending.timer = this.setTimer(() => {
2500
- if (this.pending.get(id) !== pending) return;
2501
- const timeoutError = new CodexAppServerError(
2502
- `app-server ${method} timed out`,
2503
- 'CODEX_RPC_TIMEOUT',
2504
- );
2505
- if (pending.stateChanging && pending.writeAttempted) {
2506
- this._fault(timeoutError);
2507
- return;
2508
- }
2509
- pending.sinkController?.abort(timeoutError);
2510
- this.pending.delete(id);
2511
- reject(
2512
- pending.stateChanging
2513
- ? mutationDeliveryError(pending, timeoutError)
2514
- : timeoutError,
2515
- );
2516
- }, timeoutMs);
2517
- this.pending.set(id, pending);
2518
- void this._dispatchRequest(pending, projectedParams);
2834
+ const { phase } = options;
2835
+ return dispatchRequest(this, 'hooks/list', { cwds: [manifest.ownedCwd] }, {
2836
+ internal: true,
2837
+ projectResult: (raw) => projectHookInventory(raw, manifest, phase),
2519
2838
  });
2520
2839
  }
2521
2840
 
@@ -2955,11 +3274,10 @@ class CodexAppServerClient extends EventEmitter {
2955
3274
  let projectedError;
2956
3275
  try {
2957
3276
  if (hasResult) {
2958
- projectedResult = projectRpcResult(
2959
- pending.method,
2960
- message.result,
2961
- this.cwd,
2962
- );
3277
+ const projectResult = RESULT_PROJECTORS.get(pending);
3278
+ projectedResult = typeof projectResult === 'function'
3279
+ ? projectResult(message.result)
3280
+ : projectRpcResult(pending.method, message.result, this.cwd);
2963
3281
  } else {
2964
3282
  projectedError = projectRpcError(message.error);
2965
3283
  }
@@ -3281,6 +3599,7 @@ module.exports = {
3281
3599
  attestPinnedSessionLauncher,
3282
3600
  characterizePinnedSessionLauncher,
3283
3601
  buildCodexAppServerEnv,
3602
+ normalizeCodexHookManifest: normalizeHookManifest,
3284
3603
  protocolSchema,
3285
3604
  resolveCodexTargetPin,
3286
3605
  };