@shumkov/orchestra 0.5.0 → 0.7.0

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.
@@ -30,6 +30,9 @@
30
30
 
31
31
  'use strict';
32
32
 
33
+ const path = require('node:path');
34
+ const { createHash } = require('node:crypto');
35
+
33
36
  // orchestra ships BOTH Claude-session backends. The SDK backend lives in
34
37
  // ./sdk-process; @anthropic-ai/claude-agent-sdk is an OPTIONAL dependency that
35
38
  // sdk-process lazy-requires only when a pm:'sdk' session actually starts — so
@@ -38,6 +41,297 @@
38
41
  // custom SdkProcess via createProcessFactory({ SdkProcess }); the default is ours.
39
42
  const { SdkProcess: DefaultSdkProcess } = require('./sdk-process');
40
43
  const { CliProcess } = require('./cli-process');
44
+ const { CodexProcess: DefaultCodexProcess } = require('./codex-process');
45
+ const {
46
+ assertCodexSpawnProfile,
47
+ reattestCodexStaticPolicy,
48
+ } = require('../codex/preflight');
49
+
50
+ const MAX_CODEX_ID_BYTES = 512;
51
+ const CONTROL_CHAR_RE = /[\x00-\x1f\x7f]/;
52
+ const FORBIDDEN_CODEX_CONTEXT_FIELDS = new Set([
53
+ 'cwd',
54
+ 'model',
55
+ 'effort',
56
+ 'env',
57
+ 'sessionLauncher',
58
+ 'binary',
59
+ 'codexHome',
60
+ 'permissionProfileId',
61
+ 'approvalPolicy',
62
+ 'approvalsReviewer',
63
+ 'webSearch',
64
+ 'sandbox',
65
+ 'sandboxPolicy',
66
+ 'permissions',
67
+ 'config',
68
+ 'expectedStaticProfile',
69
+ ]);
70
+
71
+ class CodexBackendNotConfiguredError extends Error {
72
+ constructor(message, options) {
73
+ super(message, options);
74
+ this.name = 'CodexBackendNotConfiguredError';
75
+ this.code = 'CODEX_BACKEND_NOT_CONFIGURED';
76
+ }
77
+ }
78
+
79
+ class RuntimeSelectionError extends Error {
80
+ constructor(runtime) {
81
+ const rendered = typeof runtime === 'string'
82
+ ? runtime
83
+ : `<${typeof runtime}>`;
84
+ super(`Unknown agent runtime '${rendered}'`);
85
+ this.name = 'RuntimeSelectionError';
86
+ this.code = 'RUNTIME_UNKNOWN';
87
+ this.runtime = rendered;
88
+ }
89
+ }
90
+
91
+ function codexConfigurationError(message, options) {
92
+ return new CodexBackendNotConfiguredError(
93
+ `Codex backend is not configured: ${message}`,
94
+ options,
95
+ );
96
+ }
97
+
98
+ function isBoundedOpaqueId(value) {
99
+ return (
100
+ typeof value === 'string'
101
+ && value.length > 0
102
+ && Buffer.byteLength(value, 'utf8') <= MAX_CODEX_ID_BYTES
103
+ && !CONTROL_CHAR_RE.test(value)
104
+ );
105
+ }
106
+
107
+ function isConstructor(value) {
108
+ if (typeof value !== 'function') return false;
109
+ try {
110
+ Reflect.construct(Object, [], value);
111
+ return true;
112
+ } catch {
113
+ return false;
114
+ }
115
+ }
116
+
117
+ function deepFreeze(value) {
118
+ if (!value || typeof value !== 'object' || Object.isFrozen(value)) {
119
+ return value;
120
+ }
121
+ for (const entry of Object.values(value)) deepFreeze(entry);
122
+ return Object.freeze(value);
123
+ }
124
+
125
+ function expectedStaticThreadPolicy(profile) {
126
+ const config = profile.expectedConfig;
127
+ const permissionProfiles = Array.isArray(config?.permissionProfiles)
128
+ ? config.permissionProfiles
129
+ : [];
130
+ const selectedProfiles = permissionProfiles.filter(
131
+ ({ id }) => id === profile.permissionProfileId,
132
+ );
133
+ if (
134
+ config?.modelProvider !== 'openai'
135
+ || config?.approvalPolicy !== 'never'
136
+ || config?.approvalsReviewer !== 'user'
137
+ || config?.defaultPermissions !== profile.permissionProfileId
138
+ || selectedProfiles.length !== 1
139
+ || selectedProfiles[0].networkEnabled !== false
140
+ ) {
141
+ throw codexConfigurationError(
142
+ 'resolved profile does not encode the required thread policy',
143
+ );
144
+ }
145
+ return deepFreeze({
146
+ modelProvider: 'openai',
147
+ approvalPolicy: 'never',
148
+ approvalsReviewer: 'user',
149
+ sandbox: {
150
+ type: 'workspaceWrite',
151
+ networkAccess: false,
152
+ writableRootCount: 1,
153
+ writableRootSha256: [
154
+ createHash('sha256').update(profile.cwd).digest('hex'),
155
+ ],
156
+ },
157
+ permissionProfile: {
158
+ id: profile.permissionProfileId,
159
+ extends: selectedProfiles[0].extends ?? null,
160
+ },
161
+ });
162
+ }
163
+
164
+ function resolveCodexProfile({
165
+ resolver,
166
+ sessionKey,
167
+ ctx,
168
+ }) {
169
+ if (typeof resolver !== 'function') {
170
+ throw codexConfigurationError(
171
+ 'codexExpectedStaticProfile resolver is required',
172
+ );
173
+ }
174
+ for (const key of FORBIDDEN_CODEX_CONTEXT_FIELDS) {
175
+ if (Object.hasOwn(ctx ?? {}, key)) {
176
+ throw codexConfigurationError(
177
+ `raw Codex spawn context field '${key}' is forbidden`,
178
+ );
179
+ }
180
+ }
181
+ const resolverContext = Object.freeze({
182
+ runtime: 'codex',
183
+ spawnProfileId: ctx?.spawnProfileId,
184
+ });
185
+ let receipt;
186
+ try {
187
+ receipt = resolver(sessionKey, resolverContext);
188
+ } catch (cause) {
189
+ throw codexConfigurationError(
190
+ 'codexExpectedStaticProfile resolver failed',
191
+ { cause },
192
+ );
193
+ }
194
+ try {
195
+ assertCodexSpawnProfile(receipt);
196
+ } catch (cause) {
197
+ throw codexConfigurationError(
198
+ 'codexExpectedStaticProfile must return a complete preflight receipt',
199
+ { cause },
200
+ );
201
+ }
202
+ if (
203
+ !isBoundedOpaqueId(ctx?.spawnProfileId)
204
+ || receipt.runtime !== 'codex'
205
+ || receipt.spawnProfileId !== ctx.spawnProfileId
206
+ ) {
207
+ throw codexConfigurationError(
208
+ 'resolved Codex runtime/spawnProfileId does not match spawn context',
209
+ );
210
+ }
211
+ const profile = receipt.expectedStaticProfile;
212
+ if (
213
+ typeof profile.cwd !== 'string'
214
+ || profile.cwd.length === 0
215
+ || profile.cwd.includes('\0')
216
+ || !path.isAbsolute(profile.cwd)
217
+ || path.normalize(profile.cwd) !== profile.cwd
218
+ ) {
219
+ throw codexConfigurationError(
220
+ 'resolved profile requires a normalized absolute cwd',
221
+ );
222
+ }
223
+ for (const field of ['permissionProfileId', 'model', 'effort']) {
224
+ if (!isBoundedOpaqueId(profile[field])) {
225
+ throw codexConfigurationError(
226
+ `resolved profile requires a bounded ${field}`,
227
+ );
228
+ }
229
+ }
230
+ return receipt;
231
+ }
232
+
233
+ function createCodexProcess({
234
+ CodexProcess,
235
+ sessionKey,
236
+ ctx,
237
+ receipt,
238
+ clientFactory,
239
+ checkpointSink,
240
+ hostIdentity,
241
+ bootSessionIdentity,
242
+ logger,
243
+ queueCap,
244
+ }) {
245
+ const profile = receipt.expectedStaticProfile;
246
+ const selectedSettings = ctx?.modelSettings;
247
+ if (
248
+ !selectedSettings
249
+ || typeof selectedSettings !== 'object'
250
+ || Array.isArray(selectedSettings)
251
+ || JSON.stringify(Object.keys(selectedSettings).sort())
252
+ !== JSON.stringify(['effort', 'model'])
253
+ || !isBoundedOpaqueId(selectedSettings.model)
254
+ || !isBoundedOpaqueId(selectedSettings.effort)
255
+ ) {
256
+ throw codexConfigurationError(
257
+ 'Codex modelSettings requires a bounded model and effort',
258
+ );
259
+ }
260
+ const matchingModels = receipt.modelCatalog.filter(
261
+ (entry) => entry?.model === selectedSettings.model,
262
+ );
263
+ if (
264
+ matchingModels.length !== 1
265
+ || !matchingModels[0].supportedReasoningEfforts
266
+ .includes(selectedSettings.effort)
267
+ ) {
268
+ throw codexConfigurationError(
269
+ 'Codex modelSettings must match the authenticated catalog',
270
+ );
271
+ }
272
+ const staticThreadPolicy = expectedStaticThreadPolicy(profile);
273
+ if (!isConstructor(CodexProcess)) {
274
+ throw codexConfigurationError('CodexProcess constructor is required');
275
+ }
276
+ if (typeof clientFactory !== 'function') {
277
+ throw codexConfigurationError('codexClientFactory is required');
278
+ }
279
+ if (typeof checkpointSink !== 'function') {
280
+ throw codexConfigurationError(
281
+ 'acknowledged codexCheckpointSink is required',
282
+ );
283
+ }
284
+ if (!isBoundedOpaqueId(hostIdentity)) {
285
+ throw codexConfigurationError('bounded codexHostIdentity is required');
286
+ }
287
+ if (!isBoundedOpaqueId(bootSessionIdentity)) {
288
+ throw codexConfigurationError(
289
+ 'bounded codexBootSessionIdentity is required',
290
+ );
291
+ }
292
+
293
+ const existingSessionId = ctx?.existingSessionId;
294
+ if (existingSessionId != null && !isBoundedOpaqueId(existingSessionId)) {
295
+ throw codexConfigurationError(
296
+ 'existingSessionId must be a bounded opaque identifier',
297
+ );
298
+ }
299
+ const spawnOptions = Object.freeze({
300
+ ...(existingSessionId == null ? {} : { existingSessionId }),
301
+ model: selectedSettings.model,
302
+ effort: selectedSettings.effort,
303
+ });
304
+ const boundClientFactory = ({ onNotification, onFault }) => clientFactory(
305
+ Object.freeze({
306
+ sessionKey,
307
+ expectedStaticProfile: profile,
308
+ onNotification,
309
+ onFault,
310
+ }),
311
+ );
312
+ const proc = new CodexProcess({
313
+ sessionKey,
314
+ chatId: ctx?.chatId ?? null,
315
+ threadId: ctx?.threadId ?? null,
316
+ label: ctx?.label || sessionKey,
317
+ cwd: profile.cwd,
318
+ clientFactory: boundClientFactory,
319
+ staticPolicyAttestor: (client) => (
320
+ reattestCodexStaticPolicy(profile, client)
321
+ ),
322
+ checkpointSink,
323
+ hostIdentity,
324
+ bootSessionIdentity,
325
+ expectedStaticPolicy: staticThreadPolicy,
326
+ modelCatalog: receipt.modelCatalog,
327
+ queueCap,
328
+ logger,
329
+ });
330
+ proc.runtime = 'codex';
331
+ proc.spawnProfileId = receipt.spawnProfileId;
332
+ proc.spawnOptions = spawnOptions;
333
+ return proc;
334
+ }
41
335
 
42
336
  // Aliases — config values that map to a different canonical backend.
43
337
  // Each alias emits ONE deprecation warn per-bot-process lifetime
@@ -117,6 +411,15 @@ function _maybeWarnR12Migration({ rawPm, canonical, chatId, threadId, chatCfg, t
117
411
  * engine knowing anything about the consumer's config shape. The resolved string
118
412
  * is what reaches CliProcess. Only the 'cli' backend uses this; the 'sdk' backend
119
413
  * gets its per-chat hint via spawnFn instead.
414
+ * @param {Function} [opts.codexClientFactory] — trusted Codex app-server client
415
+ * factory. Required only when spawnContext.runtime is exactly 'codex'.
416
+ * @param {Function} [opts.codexCheckpointSink] — acknowledged durability sink.
417
+ * @param {string} [opts.codexHostIdentity] — stable host identity.
418
+ * @param {string} [opts.codexBootSessionIdentity] — stable host-boot identity.
419
+ * @param {Function} [opts.codexExpectedStaticProfile] — trusted resolver
420
+ * `(sessionKey, identity) => receipt`, where `receipt` is the complete frozen
421
+ * value returned by `createCodexSpawnProfile`. Only runtime and spawn-profile
422
+ * identity reach the resolver; raw policy/launcher/environment context is rejected.
120
423
  * @returns {Function} processFactory(sessionKey, ctx) → Process
121
424
  */
122
425
  function createProcessFactory({
@@ -142,6 +445,12 @@ function createProcessFactory({
142
445
  surfaceName = 'the chat',
143
446
  pmDefault = 'cli', // default backend when a chat has no pm
144
447
  SdkProcess = DefaultSdkProcess, // orchestra ships this; consumer may override
448
+ CodexProcess = DefaultCodexProcess,
449
+ codexClientFactory = null,
450
+ codexCheckpointSink = null,
451
+ codexHostIdentity = null,
452
+ codexBootSessionIdentity = null,
453
+ codexExpectedStaticProfile = null,
145
454
  } = {}) {
146
455
  // spawnFn (buildSdkOptions) is only used by the deferred SDK backend; water v1 is
147
456
  // cli-only, so it is optional here (a missing SDK wiring surfaces as the SdkProcess
@@ -152,6 +461,33 @@ function createProcessFactory({
152
461
  const threadId = ctx?.threadId ?? null;
153
462
  const label = ctx?.label || sessionKey;
154
463
 
464
+ if (
465
+ ctx?.runtime != null
466
+ && ctx.runtime !== 'claude'
467
+ && ctx.runtime !== 'codex'
468
+ ) {
469
+ throw new RuntimeSelectionError(ctx.runtime);
470
+ }
471
+ if (ctx?.runtime === 'codex') {
472
+ const receipt = resolveCodexProfile({
473
+ resolver: codexExpectedStaticProfile,
474
+ sessionKey,
475
+ ctx,
476
+ });
477
+ return createCodexProcess({
478
+ CodexProcess,
479
+ sessionKey,
480
+ ctx,
481
+ receipt,
482
+ clientFactory: codexClientFactory,
483
+ checkpointSink: codexCheckpointSink,
484
+ hostIdentity: codexHostIdentity,
485
+ bootSessionIdentity: codexBootSessionIdentity,
486
+ logger,
487
+ queueCap,
488
+ });
489
+ }
490
+
155
491
  const choice = pickBackend({ config, chatId, threadId, logger, pmDefault });
156
492
 
157
493
  if (choice === 'cli') {
@@ -254,4 +590,12 @@ function _resetAliasWarnings() {
254
590
  _warnedR12Chats.clear();
255
591
  }
256
592
 
257
- module.exports = { createProcessFactory, pickBackend, _resetAliasWarnings, ALIASES, CANONICAL_BACKENDS };
593
+ module.exports = {
594
+ createProcessFactory,
595
+ pickBackend,
596
+ _resetAliasWarnings,
597
+ ALIASES,
598
+ CANONICAL_BACKENDS,
599
+ CodexBackendNotConfiguredError,
600
+ RuntimeSelectionError,
601
+ };