ultracode-for-codex 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,158 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and
10
+ distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright
13
+ owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities
16
+ that control, are controlled by, or are under common control with that entity.
17
+ For the purposes of this definition, "control" means (i) the power, direct or
18
+ indirect, to cause the direction or management of such entity, whether by
19
+ contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
20
+ outstanding shares, or (iii) beneficial ownership of such entity.
21
+
22
+ "You" (or "Your") shall mean an individual or Legal Entity exercising
23
+ permissions granted by this License.
24
+
25
+ "Source" form shall mean the preferred form for making modifications, including
26
+ but not limited to software source code, documentation source, and configuration
27
+ files.
28
+
29
+ "Object" form shall mean any form resulting from mechanical transformation or
30
+ translation of a Source form, including but not limited to compiled object code,
31
+ generated documentation, and conversions to other media types.
32
+
33
+ "Work" shall mean the work of authorship, whether in Source or Object form,
34
+ made available under the License, as indicated by a copyright notice that is
35
+ included in or attached to the work.
36
+
37
+ "Derivative Works" shall mean any work, whether in Source or Object form, that
38
+ is based on (or derived from) the Work and for which the editorial revisions,
39
+ annotations, elaborations, or other modifications represent, as a whole, an
40
+ original work of authorship. For the purposes of this License, Derivative Works
41
+ shall not include works that remain separable from, or merely link (or bind by
42
+ name) to the interfaces of, the Work and Derivative Works thereof.
43
+
44
+ "Contribution" shall mean any work of authorship, including the original version
45
+ of the Work and any modifications or additions to that Work or Derivative Works
46
+ thereof, that is intentionally submitted to Licensor for inclusion in the Work by
47
+ the copyright owner or by an individual or Legal Entity authorized to submit on
48
+ behalf of the copyright owner. For the purposes of this definition, "submitted"
49
+ means any form of electronic, verbal, or written communication sent to the
50
+ Licensor or its representatives, including but not limited to communication on
51
+ electronic mailing lists, source code control systems, and issue tracking
52
+ systems that are managed by, or on behalf of, the Licensor for the purpose of
53
+ discussing and improving the Work, but excluding communication that is
54
+ conspicuously marked or otherwise designated in writing by the copyright owner
55
+ as "Not a Contribution."
56
+
57
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf
58
+ of whom a Contribution has been received by Licensor and subsequently
59
+ incorporated within the Work.
60
+
61
+ 2. Grant of Copyright License. Subject to the terms and conditions of this
62
+ License, each Contributor hereby grants to You a perpetual, worldwide,
63
+ non-exclusive, no-charge, royalty-free, irrevocable copyright license to
64
+ reproduce, prepare Derivative Works of, publicly display, publicly perform,
65
+ sublicense, and distribute the Work and such Derivative Works in Source or
66
+ Object form.
67
+
68
+ 3. Grant of Patent License. Subject to the terms and conditions of this License,
69
+ each Contributor hereby grants to You a perpetual, worldwide, non-exclusive,
70
+ no-charge, royalty-free, irrevocable (except as stated in this section) patent
71
+ license to make, have made, use, offer to sell, sell, import, and otherwise
72
+ transfer the Work, where such license applies only to those patent claims
73
+ licensable by such Contributor that are necessarily infringed by their
74
+ Contribution(s) alone or by combination of their Contribution(s) with the Work
75
+ to which such Contribution(s) was submitted. If You institute patent litigation
76
+ against any entity (including a cross-claim or counterclaim in a lawsuit)
77
+ alleging that the Work or a Contribution incorporated within the Work
78
+ constitutes direct or contributory patent infringement, then any patent licenses
79
+ granted to You under this License for that Work shall terminate as of the date
80
+ such litigation is filed.
81
+
82
+ 4. Redistribution. You may reproduce and distribute copies of the Work or
83
+ Derivative Works thereof in any medium, with or without modifications, and in
84
+ Source or Object form, provided that You meet the following conditions:
85
+
86
+ (a) You must give any other recipients of the Work or Derivative Works a copy of
87
+ this License; and
88
+
89
+ (b) You must cause any modified files to carry prominent notices stating that
90
+ You changed the files; and
91
+
92
+ (c) You must retain, in the Source form of any Derivative Works that You
93
+ distribute, all copyright, patent, trademark, and attribution notices from the
94
+ Source form of the Work, excluding those notices that do not pertain to any part
95
+ of the Derivative Works; and
96
+
97
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then
98
+ any Derivative Works that You distribute must include a readable copy of the
99
+ attribution notices contained within such NOTICE file, excluding those notices
100
+ that do not pertain to any part of the Derivative Works, in at least one of the
101
+ following places: within a NOTICE text file distributed as part of the Derivative
102
+ Works; within the Source form or documentation, if provided along with the
103
+ Derivative Works; or, within a display generated by the Derivative Works, if and
104
+ wherever such third-party notices normally appear. The contents of the NOTICE
105
+ file are for informational purposes only and do not modify the License. You may
106
+ add Your own attribution notices within Derivative Works that You distribute,
107
+ alongside or as an addendum to the NOTICE text from the Work, provided that such
108
+ additional attribution notices cannot be construed as modifying the License.
109
+
110
+ You may add Your own copyright statement to Your modifications and may provide
111
+ additional or different license terms and conditions for use, reproduction, or
112
+ distribution of Your modifications, or for any such Derivative Works as a whole,
113
+ provided Your use, reproduction, and distribution of the Work otherwise complies
114
+ with the conditions stated in this License.
115
+
116
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any
117
+ Contribution intentionally submitted for inclusion in the Work by You to the
118
+ Licensor shall be under the terms and conditions of this License, without any
119
+ additional terms or conditions. Notwithstanding the above, nothing herein shall
120
+ supersede or modify the terms of any separate license agreement you may have
121
+ executed with Licensor regarding such Contributions.
122
+
123
+ 6. Trademarks. This License does not grant permission to use the trade names,
124
+ trademarks, service marks, or product names of the Licensor, except as required
125
+ for reasonable and customary use in describing the origin of the Work and
126
+ reproducing the content of the NOTICE file.
127
+
128
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in
129
+ writing, Licensor provides the Work on an "AS IS" BASIS, WITHOUT WARRANTIES OR
130
+ CONDITIONS OF ANY KIND, either express or implied, including, without
131
+ limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT,
132
+ MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely
133
+ responsible for determining the appropriateness of using or redistributing the
134
+ Work and assume any risks associated with Your exercise of permissions under
135
+ this License.
136
+
137
+ 8. Limitation of Liability. In no event and under no legal theory, whether in
138
+ tort (including negligence), contract, or otherwise, unless required by
139
+ applicable law (such as deliberate and grossly negligent acts) or agreed to in
140
+ writing, shall any Contributor be liable to You for damages, including any
141
+ direct, indirect, special, incidental, or consequential damages of any character
142
+ arising as a result of this License or out of the use or inability to use the
143
+ Work (including but not limited to damages for loss of goodwill, work stoppage,
144
+ computer failure or malfunction, or any and all other commercial damages or
145
+ losses), even if such Contributor has been advised of the possibility of such
146
+ damages.
147
+
148
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or
149
+ Derivative Works thereof, You may choose to offer, and charge a fee for,
150
+ acceptance of support, warranty, indemnity, or other liability obligations or
151
+ rights consistent with this License. However, in accepting such obligations, You
152
+ may act only on Your own behalf and on Your sole responsibility, not on behalf
153
+ of any other Contributor, and only if You agree to indemnify, defend, and hold
154
+ each Contributor harmless for any liability incurred by, or claims asserted
155
+ against, such Contributor by reason of your accepting any such warranty or
156
+ additional liability.
157
+
158
+ END OF TERMS AND CONDITIONS
package/README.md CHANGED
@@ -26,7 +26,7 @@ npm run pack:ultracode-for-codex
26
26
  Install the tarball from a target project:
27
27
 
28
28
  ```bash
29
- npm install --save-dev /path/to/ultracode-for-codex-0.2.0.tgz
29
+ npm install --save-dev /path/to/ultracode-for-codex-0.2.2.tgz
30
30
  ```
31
31
 
32
32
  Run a workflow:
@@ -118,6 +118,10 @@ want Codex to auto-load the package boundaries and verification routine.
118
118
  - The only production backend is Codex app-server over stdio.
119
119
  - Direct provider credentials are stripped from the Codex child process
120
120
  environment.
121
+ - Codex subagents run against the requested workflow cwd and receive bounded
122
+ read-only workspace tools for text file reads and directory listings.
123
+ - Built-in `code-review` injects deterministic workspace context before calling
124
+ its subagent so file-specific prompts carry local evidence into the review.
121
125
  - Workflow execution is local and command-owned; settings default to OS
122
126
  background execution and `--execution attached` keeps the process connected
123
127
  until completion.
@@ -31,7 +31,7 @@ npm exec -- ultracode-for-codex --llm-guide
31
31
  For source-checkout validation, install the generated tarball instead:
32
32
 
33
33
  ```bash
34
- npm install --save-dev ./ultracode-for-codex-0.2.0.tgz
34
+ npm install --save-dev ./ultracode-for-codex-0.2.2.tgz
35
35
  ```
36
36
 
37
37
  Optional Codex companion skill:
@@ -104,6 +104,10 @@ Useful controls:
104
104
  - Keep stdout reserved for the final JSON result; stream progress records to
105
105
  stderr as JSONL unless a human chooses `--progress plain`.
106
106
  - Strip direct provider credentials from child CLI environments.
107
+ - Run Codex subagents against the requested workflow cwd and provide bounded
108
+ read-only workspace tools for text file reads and directory listings.
109
+ - Built-in `code-review` adds deterministic workspace context before the agent
110
+ call, prioritizing files explicitly mentioned in the prompt.
107
111
  - Install consumers from a packaged artifact.
108
112
  - Keep `journalPath`, `journal.jsonl`, and journal contents out of CLI output.
109
113
  Local runtime state may still contain runtime-owned
@@ -30,6 +30,7 @@ export declare class CodexSubagentBackend implements SubagentBackend {
30
30
  private readonly pending;
31
31
  private readonly turnWaiters;
32
32
  private readonly bufferedTurnStates;
33
+ private readonly threadReadRoots;
33
34
  private isolation;
34
35
  constructor(options: CodexSubagentBackendOptions);
35
36
  generate(request: SubagentRequest, signal?: AbortSignal): Promise<SubagentResult>;
@@ -43,6 +44,10 @@ export declare class CodexSubagentBackend implements SubagentBackend {
43
44
  private notify;
44
45
  private handleLine;
45
46
  private respondToServerRequest;
47
+ private writeResponse;
48
+ private handleDynamicToolCall;
49
+ private readWorkspaceFile;
50
+ private listWorkspaceDirectory;
46
51
  private handleNotification;
47
52
  private waitForTurn;
48
53
  private markWaiterCompleted;
@@ -1,8 +1,8 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { randomUUID } from 'node:crypto';
3
- import { copyFile, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
3
+ import { copyFile, mkdir, mkdtemp, readdir, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises';
4
4
  import { homedir, tmpdir } from 'node:os';
5
- import { join } from 'node:path';
5
+ import { isAbsolute, join, relative, resolve } from 'node:path';
6
6
  import readline from 'node:readline';
7
7
  import { codexDefaultReasoningEffort, codexDefaultVerbosity, } from '../settings.js';
8
8
  import { estimateTokens } from '../runtime/types.js';
@@ -10,6 +10,9 @@ import { codexChildProcessEnv } from './env.js';
10
10
  const USAGE_NOTIFICATION_GRACE_MS = 100;
11
11
  const BUFFERED_TURN_STATE_TTL_MS = 30_000;
12
12
  const FALLBACK_CODEX_MODEL = 'gpt-5.5';
13
+ const WORKSPACE_DYNAMIC_TOOL_NAMESPACE = 'workspace';
14
+ const MAX_WORKSPACE_TOOL_READ_BYTES = 200_000;
15
+ const MAX_WORKSPACE_TOOL_DIRECTORY_ENTRIES = 200;
13
16
  const DISABLED_CODEX_CONTEXT_FEATURES = [
14
17
  'apps',
15
18
  'browser_use',
@@ -22,6 +25,46 @@ const DISABLED_CODEX_CONTEXT_FEATURES = [
22
25
  'shell_tool',
23
26
  'workspace_dependencies',
24
27
  ];
28
+ const WORKSPACE_DYNAMIC_TOOLS = [
29
+ {
30
+ type: 'namespace',
31
+ name: WORKSPACE_DYNAMIC_TOOL_NAMESPACE,
32
+ description: 'Read-only access to files in the active workflow workspace.',
33
+ tools: [
34
+ {
35
+ type: 'function',
36
+ name: 'read_file',
37
+ description: 'Read a UTF-8 text file inside the active workflow workspace.',
38
+ inputSchema: {
39
+ type: 'object',
40
+ additionalProperties: false,
41
+ properties: {
42
+ path: {
43
+ type: 'string',
44
+ description: 'Relative path inside the active workspace.',
45
+ },
46
+ },
47
+ required: ['path'],
48
+ },
49
+ },
50
+ {
51
+ type: 'function',
52
+ name: 'list_directory',
53
+ description: 'List direct entries in a directory inside the active workflow workspace.',
54
+ inputSchema: {
55
+ type: 'object',
56
+ additionalProperties: false,
57
+ properties: {
58
+ path: {
59
+ type: 'string',
60
+ description: 'Relative directory path inside the active workspace. Defaults to the workspace root.',
61
+ },
62
+ },
63
+ },
64
+ },
65
+ ],
66
+ },
67
+ ];
25
68
  export class CodexSubagentBackend {
26
69
  name = 'codex-subagent';
27
70
  model;
@@ -39,6 +82,7 @@ export class CodexSubagentBackend {
39
82
  pending = new Map();
40
83
  turnWaiters = new Map();
41
84
  bufferedTurnStates = new Map();
85
+ threadReadRoots = new Map();
42
86
  isolation = null;
43
87
  constructor(options) {
44
88
  this.command = options.command ?? 'codex';
@@ -70,7 +114,7 @@ export class CodexSubagentBackend {
70
114
  if (signal)
71
115
  signal.addEventListener('abort', onAbort, { once: true });
72
116
  try {
73
- const cwd = request.worktreePath ?? this.isolation?.workDir ?? this.cwd;
117
+ const cwd = request.worktreePath ?? this.cwd;
74
118
  threadId = await this.startThread(reasoningEffort, this.verbosity, Boolean(structuredTool), cwd, Boolean(request.worktreePath));
75
119
  const turn = await this.send('turn/start', {
76
120
  threadId,
@@ -121,6 +165,7 @@ export class CodexSubagentBackend {
121
165
  }
122
166
  this.turnWaiters.clear();
123
167
  this.clearBufferedTurnStates();
168
+ this.threadReadRoots.clear();
124
169
  this.lineReader?.close();
125
170
  this.child?.kill('SIGTERM');
126
171
  this.child = null;
@@ -192,7 +237,7 @@ export class CodexSubagentBackend {
192
237
  approvalPolicy: 'never',
193
238
  sandbox: workspaceWrite ? 'workspace-write' : 'read-only',
194
239
  environments: [],
195
- dynamicTools: [],
240
+ dynamicTools: WORKSPACE_DYNAMIC_TOOLS,
196
241
  ephemeral: true,
197
242
  baseInstructions: 'Ultracode workflow subagent. Produce only the workflow agent return value.',
198
243
  developerInstructions: structured
@@ -211,9 +256,11 @@ export class CodexSubagentBackend {
211
256
  const threadId = readPath(thread, ['result', 'thread', 'id']);
212
257
  if (!threadId)
213
258
  throw new Error('codex app-server did not return a thread id');
259
+ this.threadReadRoots.set(threadId, await realpath(cwd).catch(() => resolve(cwd)));
214
260
  return threadId;
215
261
  }
216
262
  archiveThread(threadId) {
263
+ this.threadReadRoots.delete(threadId);
217
264
  void this.send('thread/archive', { threadId }).catch(() => undefined);
218
265
  }
219
266
  async cleanupIsolation() {
@@ -267,20 +314,104 @@ export class CodexSubagentBackend {
267
314
  return;
268
315
  }
269
316
  if (id !== null && typeof message.method === 'string') {
270
- this.respondToServerRequest(id, message.method);
317
+ this.respondToServerRequest(id, message.method, message.params);
271
318
  return;
272
319
  }
273
320
  if (typeof message.method === 'string')
274
321
  this.handleNotification(message.method, message.params);
275
322
  }
276
- respondToServerRequest(id, method) {
277
- const result = method.includes('requestApproval') ? { decision: 'decline' } : undefined;
278
- this.child?.stdin.write(`${JSON.stringify({
279
- id,
280
- ...(result
281
- ? { result }
282
- : { error: { code: -32601, message: `Unsupported server request: ${method}` } }),
283
- })}\n`);
323
+ respondToServerRequest(id, method, params) {
324
+ void (async () => {
325
+ if (method.includes('requestApproval')) {
326
+ this.writeResponse(id, { result: { decision: 'decline' } });
327
+ return;
328
+ }
329
+ if (method === 'item/tool/call') {
330
+ this.writeResponse(id, { result: await this.handleDynamicToolCall(params) });
331
+ return;
332
+ }
333
+ this.writeResponse(id, {
334
+ error: { code: -32601, message: `Unsupported server request: ${method}` },
335
+ });
336
+ })().catch((err) => {
337
+ this.writeResponse(id, {
338
+ error: { code: -32603, message: workflowToolErrorMessage(err) },
339
+ });
340
+ });
341
+ }
342
+ writeResponse(id, response) {
343
+ this.child?.stdin.write(`${JSON.stringify({ id, ...response })}\n`);
344
+ }
345
+ async handleDynamicToolCall(params) {
346
+ const data = asRecord(params);
347
+ const threadId = typeof data?.threadId === 'string' ? data.threadId : '';
348
+ const root = this.threadReadRoots.get(threadId);
349
+ if (!root)
350
+ return dynamicToolFailure('Workspace root is unavailable for this thread.');
351
+ const namespace = data?.namespace === null || typeof data?.namespace === 'string'
352
+ ? data.namespace
353
+ : null;
354
+ const rawTool = typeof data?.tool === 'string' ? data.tool : '';
355
+ const tool = namespace === WORKSPACE_DYNAMIC_TOOL_NAMESPACE
356
+ ? rawTool
357
+ : namespace === null && (rawTool === 'read_file' || rawTool === 'list_directory')
358
+ ? rawTool
359
+ : rawTool.startsWith(`${WORKSPACE_DYNAMIC_TOOL_NAMESPACE}.`)
360
+ ? rawTool.slice(WORKSPACE_DYNAMIC_TOOL_NAMESPACE.length + 1)
361
+ : '';
362
+ const args = asRecord(data?.arguments) ?? {};
363
+ if (tool === 'read_file') {
364
+ return await this.readWorkspaceFile(root, args).catch((err) => dynamicToolFailure(workflowToolErrorMessage(err)));
365
+ }
366
+ if (tool === 'list_directory') {
367
+ return await this.listWorkspaceDirectory(root, args).catch((err) => dynamicToolFailure(workflowToolErrorMessage(err)));
368
+ }
369
+ return dynamicToolFailure(`Unsupported workspace tool: ${namespace ? `${namespace}.` : ''}${rawTool}`);
370
+ }
371
+ async readWorkspaceFile(root, args) {
372
+ const requestedPath = typeof args.path === 'string' ? args.path : '';
373
+ if (!requestedPath.trim())
374
+ return dynamicToolFailure('read_file requires a non-empty path string.');
375
+ const target = await resolveWorkspaceToolPath(root, requestedPath);
376
+ const fileStat = await stat(target.path).catch((err) => {
377
+ throw new Error(`Cannot stat ${target.relativePath}: ${workflowToolErrorMessage(err)}`);
378
+ });
379
+ if (!fileStat.isFile())
380
+ return dynamicToolFailure(`${target.relativePath} is not a file.`);
381
+ if (fileStat.size > MAX_WORKSPACE_TOOL_READ_BYTES) {
382
+ return dynamicToolFailure(`${target.relativePath} is ${fileStat.size} bytes; limit is ${MAX_WORKSPACE_TOOL_READ_BYTES} bytes.`);
383
+ }
384
+ const text = await readFile(target.path, 'utf8').catch((err) => {
385
+ throw new Error(`Cannot read ${target.relativePath}: ${workflowToolErrorMessage(err)}`);
386
+ });
387
+ if (text.includes('\0'))
388
+ return dynamicToolFailure(`${target.relativePath} appears to be binary.`);
389
+ return dynamicToolSuccess([
390
+ `path: ${target.relativePath}`,
391
+ `bytes: ${Buffer.byteLength(text, 'utf8')}`,
392
+ '',
393
+ text,
394
+ ].join('\n'));
395
+ }
396
+ async listWorkspaceDirectory(root, args) {
397
+ const requestedPath = typeof args.path === 'string' && args.path.trim() ? args.path : '.';
398
+ const target = await resolveWorkspaceToolPath(root, requestedPath);
399
+ const entries = await readdir(target.path, { withFileTypes: true }).catch((err) => {
400
+ throw new Error(`Cannot list ${target.relativePath}: ${workflowToolErrorMessage(err)}`);
401
+ });
402
+ const sorted = entries
403
+ .map((entry) => `${entry.name}${entry.isDirectory() ? '/' : ''}`)
404
+ .sort((left, right) => left.localeCompare(right));
405
+ const visible = sorted.slice(0, MAX_WORKSPACE_TOOL_DIRECTORY_ENTRIES);
406
+ const truncated = sorted.length > visible.length
407
+ ? `\n... ${sorted.length - visible.length} more entries omitted`
408
+ : '';
409
+ return dynamicToolSuccess([
410
+ `path: ${target.relativePath}`,
411
+ `entries: ${sorted.length}`,
412
+ '',
413
+ ...visible,
414
+ ].join('\n') + truncated);
284
415
  }
285
416
  handleNotification(method, params) {
286
417
  const data = asRecord(params);
@@ -544,6 +675,42 @@ function readPath(value, path) {
544
675
  }
545
676
  return current;
546
677
  }
678
+ async function resolveWorkspaceToolPath(root, requestedPath) {
679
+ const requested = requestedPath.trim();
680
+ const candidate = isAbsolute(requested) ? resolve(requested) : resolve(root, requested);
681
+ if (!pathInsideOrEqual(root, candidate)) {
682
+ throw new Error(`Path escapes workspace: ${requestedPath}`);
683
+ }
684
+ const canonicalPath = await realpath(candidate).catch((err) => {
685
+ throw new Error(`Path not found: ${requestedPath} (${workflowToolErrorMessage(err)})`);
686
+ });
687
+ if (!pathInsideOrEqual(root, canonicalPath)) {
688
+ throw new Error(`Path escapes workspace: ${requestedPath}`);
689
+ }
690
+ return {
691
+ path: canonicalPath,
692
+ relativePath: relative(root, canonicalPath) || '.',
693
+ };
694
+ }
695
+ function pathInsideOrEqual(parent, child) {
696
+ const candidate = relative(parent, child);
697
+ return candidate === '' || (!candidate.startsWith('..') && !isAbsolute(candidate));
698
+ }
699
+ function dynamicToolSuccess(text) {
700
+ return {
701
+ success: true,
702
+ contentItems: [{ type: 'inputText', text }],
703
+ };
704
+ }
705
+ function dynamicToolFailure(text) {
706
+ return {
707
+ success: false,
708
+ contentItems: [{ type: 'inputText', text }],
709
+ };
710
+ }
711
+ function workflowToolErrorMessage(err) {
712
+ return err instanceof Error ? err.message : String(err);
713
+ }
547
714
  export function usageFromCodexTokenUsage(value) {
548
715
  const usage = asRecord(value);
549
716
  const last = asRecord(usage?.last);
@@ -241,6 +241,7 @@ export declare class WorkflowTaskRegistry implements WorkflowRuntime {
241
241
  private runTask;
242
242
  private createVmGlobals;
243
243
  private runAgent;
244
+ private workspaceContext;
244
245
  private runAgentInner;
245
246
  private createAgentWorktree;
246
247
  private finalizeAgentWorktree;
@@ -1,6 +1,6 @@
1
1
  import { execFile } from 'node:child_process';
2
2
  import { createHash, randomUUID } from 'node:crypto';
3
- import { chmod, mkdir, readdir, readFile, realpath, rm, writeFile } from 'node:fs/promises';
3
+ import { chmod, mkdir, readdir, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises';
4
4
  import { homedir } from 'node:os';
5
5
  import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
6
6
  import { promisify } from 'node:util';
@@ -12,6 +12,9 @@ const MAX_AGENT_CALLS = 1000;
12
12
  const MAX_PARALLELISM = 16;
13
13
  const DEFAULT_AGENT_STALL_TIMEOUT_MS = 180_000;
14
14
  const DEFAULT_AGENT_STALL_RETRY_LIMIT = 5;
15
+ const DEFAULT_WORKSPACE_CONTEXT_MAX_FILES = 24;
16
+ const DEFAULT_WORKSPACE_CONTEXT_MAX_FILE_BYTES = 12_000;
17
+ const DEFAULT_WORKSPACE_CONTEXT_MAX_BYTES = 80_000;
15
18
  const execFileAsync = promisify(execFile);
16
19
  const PROJECT_WORKFLOW_DIRS = ['.codex/workflows'];
17
20
  const WORKFLOW_PERMISSION_REQUIRED_SOURCES = new Set(['script_path', 'project', 'user', 'plugin']);
@@ -54,6 +57,48 @@ const JSON_SCHEMA_KEYS = new Set([
54
57
  'title',
55
58
  'type',
56
59
  ]);
60
+ const WORKSPACE_CONTEXT_EXCLUDED_DIRS = new Set([
61
+ '.git',
62
+ '.next',
63
+ '.turbo',
64
+ '.ultracode-for-codex',
65
+ 'artifacts',
66
+ 'build',
67
+ 'coverage',
68
+ 'dist',
69
+ 'node_modules',
70
+ 'out',
71
+ ]);
72
+ const WORKSPACE_CONTEXT_ALLOWED_EXTENSIONS = new Set([
73
+ '.cjs',
74
+ '.css',
75
+ '.go',
76
+ '.html',
77
+ '.js',
78
+ '.json',
79
+ '.jsx',
80
+ '.md',
81
+ '.mjs',
82
+ '.py',
83
+ '.rs',
84
+ '.sh',
85
+ '.toml',
86
+ '.ts',
87
+ '.tsx',
88
+ '.txt',
89
+ '.yaml',
90
+ '.yml',
91
+ ]);
92
+ const WORKSPACE_CONTEXT_PRIORITY_FILES = new Set([
93
+ 'AGENTS.md',
94
+ 'CONTRACT.md',
95
+ 'IMPLEMENTATION_MAP.html',
96
+ 'README.md',
97
+ 'SKILL.md',
98
+ 'ULTRACODE_INSTALL.md',
99
+ 'package.json',
100
+ 'tsconfig.json',
101
+ ]);
57
102
  const DEFAULT_BUILTIN_WORKFLOWS = [
58
103
  {
59
104
  name: 'code-review',
@@ -65,7 +110,14 @@ const input = args && typeof args === "object" ? args : {};
65
110
  const prompt = typeof input.prompt === "string" && input.prompt.trim()
66
111
  ? input.prompt
67
112
  : "Review the current repository for correctness risks.";
68
- return await agent(prompt, { label: "code-review" });`,
113
+ const context = await workspaceContext({ query: prompt });
114
+ return await agent([
115
+ prompt,
116
+ "",
117
+ "Use the deterministic workspace context below as primary evidence. Mention any missing evidence explicitly.",
118
+ "",
119
+ context
120
+ ].join("\\n"), { label: "code-review" });`,
69
121
  },
70
122
  {
71
123
  name: 'batch',
@@ -824,6 +876,9 @@ export class WorkflowTaskRegistry {
824
876
  host.pipeline = hardenCallable((items, ...stages) => {
825
877
  return this.trackWorkflowPromise(ctx, this.pipeline(ctx, items, stages));
826
878
  });
879
+ host.workspaceContext = hardenCallable((options) => {
880
+ return this.trackWorkflowPromise(ctx, this.workspaceContext(ctx, options));
881
+ });
827
882
  host.phase = hardenCallable((title) => this.phase(ctx, title));
828
883
  host.log = hardenCallable(log);
829
884
  host.consoleLog = hardenCallable((...values) => {
@@ -863,6 +918,12 @@ export class WorkflowTaskRegistry {
863
918
  operation.catch(() => undefined);
864
919
  return this.trackWorkflowPromise(ctx, operation);
865
920
  }
921
+ async workspaceContext(ctx, options) {
922
+ if (ctx.controller.signal.aborted || ctx.task.status !== 'running') {
923
+ throw workflowInputError('Workflow is aborted.');
924
+ }
925
+ return await buildWorkspaceContext(this.options.cwd ?? process.cwd(), normalizeWorkspaceContextOptions(options));
926
+ }
866
927
  async runAgentInner(ctx, prompt, options) {
867
928
  if (typeof prompt !== 'string' || prompt.trim() === '') {
868
929
  throw workflowInputError('agent(prompt) requires a non-empty string prompt.');
@@ -1482,6 +1543,198 @@ async function gitOutput(cwd, args) {
1482
1543
  throw new Error(message);
1483
1544
  }
1484
1545
  }
1546
+ async function buildWorkspaceContext(cwd, options) {
1547
+ const root = await workspaceContextRoot(cwd);
1548
+ const gitStatus = await gitOutput(root, ['status', '--short']).catch(() => '');
1549
+ const explicitPaths = [
1550
+ ...options.files,
1551
+ ...extractMentionedWorkspacePaths(options.query ?? ''),
1552
+ ];
1553
+ const changedPaths = pathsFromGitStatus(gitStatus);
1554
+ const listedPaths = await listWorkspaceContextCandidates(root);
1555
+ const candidates = uniqueStrings([
1556
+ ...explicitPaths,
1557
+ ...changedPaths,
1558
+ ...WORKSPACE_CONTEXT_PRIORITY_FILES,
1559
+ ...listedPaths,
1560
+ ]).filter(shouldIncludeWorkspaceContextPath);
1561
+ const fileBlocks = [];
1562
+ let usedBytes = 0;
1563
+ for (const candidate of candidates) {
1564
+ if (fileBlocks.length >= options.maxFiles)
1565
+ break;
1566
+ const block = await workspaceContextFileBlock(root, candidate, options.maxFileBytes).catch(() => null);
1567
+ if (!block)
1568
+ continue;
1569
+ const blockBytes = Buffer.byteLength(block, 'utf8');
1570
+ if (usedBytes + blockBytes > options.maxBytes) {
1571
+ if (fileBlocks.length > 0)
1572
+ break;
1573
+ fileBlocks.push(block.slice(0, options.maxBytes));
1574
+ break;
1575
+ }
1576
+ fileBlocks.push(block);
1577
+ usedBytes += blockBytes;
1578
+ }
1579
+ return [
1580
+ '## Workspace Context',
1581
+ `Root: ${root}`,
1582
+ '',
1583
+ '### Git Status',
1584
+ gitStatus.trim() ? gitStatus : '(clean or unavailable)',
1585
+ '',
1586
+ '### Included Files',
1587
+ fileBlocks.length ? fileBlocks.join('\n\n') : '(no readable text files selected)',
1588
+ ].join('\n');
1589
+ }
1590
+ function normalizeWorkspaceContextOptions(value) {
1591
+ const options = asRecord(value) ?? {};
1592
+ const query = typeof options.query === 'string' ? options.query : undefined;
1593
+ const files = Array.isArray(options.files)
1594
+ ? options.files.filter((item) => typeof item === 'string' && item.trim() !== '')
1595
+ : [];
1596
+ return {
1597
+ ...(query ? { query } : {}),
1598
+ files,
1599
+ maxFiles: boundedPositiveInteger(options.maxFiles, DEFAULT_WORKSPACE_CONTEXT_MAX_FILES, 1, 100),
1600
+ maxFileBytes: boundedPositiveInteger(options.maxFileBytes, DEFAULT_WORKSPACE_CONTEXT_MAX_FILE_BYTES, 1_000, 50_000),
1601
+ maxBytes: boundedPositiveInteger(options.maxBytes, DEFAULT_WORKSPACE_CONTEXT_MAX_BYTES, 10_000, 200_000),
1602
+ };
1603
+ }
1604
+ function boundedPositiveInteger(value, fallback, min, max) {
1605
+ if (typeof value !== 'number' || !Number.isFinite(value))
1606
+ return fallback;
1607
+ return Math.max(min, Math.min(max, Math.floor(value)));
1608
+ }
1609
+ async function workspaceContextRoot(cwd) {
1610
+ try {
1611
+ return await gitOutput(cwd, ['rev-parse', '--show-toplevel']);
1612
+ }
1613
+ catch {
1614
+ return await realpath(cwd).catch(() => resolve(cwd));
1615
+ }
1616
+ }
1617
+ async function listWorkspaceContextCandidates(root) {
1618
+ try {
1619
+ return splitLines(await gitOutput(root, ['ls-files', '--cached', '--others', '--exclude-standard']));
1620
+ }
1621
+ catch {
1622
+ return await walkWorkspaceContextFiles(root);
1623
+ }
1624
+ }
1625
+ async function walkWorkspaceContextFiles(root) {
1626
+ const found = [];
1627
+ async function walk(dir) {
1628
+ if (found.length >= 500)
1629
+ return;
1630
+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
1631
+ for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
1632
+ if (found.length >= 500)
1633
+ return;
1634
+ if (WORKSPACE_CONTEXT_EXCLUDED_DIRS.has(entry.name))
1635
+ continue;
1636
+ const fullPath = join(dir, entry.name);
1637
+ if (entry.isDirectory()) {
1638
+ await walk(fullPath);
1639
+ continue;
1640
+ }
1641
+ if (entry.isFile())
1642
+ found.push(relative(root, fullPath));
1643
+ }
1644
+ }
1645
+ await walk(root);
1646
+ return found;
1647
+ }
1648
+ function extractMentionedWorkspacePaths(query) {
1649
+ const out = new Set();
1650
+ for (const file of WORKSPACE_CONTEXT_PRIORITY_FILES) {
1651
+ if (query.includes(file))
1652
+ out.add(file);
1653
+ }
1654
+ const matches = query.match(/[A-Za-z0-9_.@+-]+(?:\/[A-Za-z0-9_.@+-]+)+(?:\.[A-Za-z0-9]+)?(?::\d+)?/g) ?? [];
1655
+ for (const match of matches) {
1656
+ if (match.includes('://'))
1657
+ continue;
1658
+ out.add(match.replace(/:\d+$/, ''));
1659
+ }
1660
+ return [...out];
1661
+ }
1662
+ function pathsFromGitStatus(status) {
1663
+ const paths = [];
1664
+ for (const line of status.split(/\r?\n/).filter(Boolean)) {
1665
+ const rawPath = line.length > 3 ? line.slice(3).trim() : line.trim();
1666
+ if (!rawPath)
1667
+ continue;
1668
+ const path = rawPath.includes(' -> ') ? rawPath.split(' -> ').at(-1) ?? rawPath : rawPath;
1669
+ paths.push(path.replace(/^"|"$/g, ''));
1670
+ }
1671
+ return paths;
1672
+ }
1673
+ async function workspaceContextFileBlock(root, requestedPath, maxFileBytes) {
1674
+ const resolved = await resolveWorkspaceContextPath(root, requestedPath);
1675
+ if (!resolved)
1676
+ return null;
1677
+ const fileStat = await stat(resolved.path).catch(() => null);
1678
+ if (!fileStat?.isFile() || fileStat.size > maxFileBytes)
1679
+ return null;
1680
+ const text = await readFile(resolved.path, 'utf8').catch(() => null);
1681
+ if (text === null || text.includes('\0'))
1682
+ return null;
1683
+ return [
1684
+ `--- ${resolved.relativePath} (${fileStat.size} bytes) ---`,
1685
+ numberWorkspaceContextLines(text),
1686
+ ].join('\n');
1687
+ }
1688
+ async function resolveWorkspaceContextPath(root, requestedPath) {
1689
+ const requested = requestedPath.trim();
1690
+ if (!requested)
1691
+ return null;
1692
+ const candidate = isAbsolute(requested) ? resolve(requested) : resolve(root, requested);
1693
+ if (!pathInsideOrEqual(root, candidate))
1694
+ return null;
1695
+ const canonical = await realpath(candidate).catch(() => null);
1696
+ if (!canonical || !pathInsideOrEqual(root, canonical))
1697
+ return null;
1698
+ return {
1699
+ path: canonical,
1700
+ relativePath: relative(root, canonical) || '.',
1701
+ };
1702
+ }
1703
+ function shouldIncludeWorkspaceContextPath(path) {
1704
+ const normalized = path.replaceAll('\\', '/').replace(/^\.\/+/, '');
1705
+ if (!normalized || normalized.startsWith('../') || normalized.includes('/../'))
1706
+ return false;
1707
+ const parts = normalized.split('/');
1708
+ if (parts.some((part) => WORKSPACE_CONTEXT_EXCLUDED_DIRS.has(part)))
1709
+ return false;
1710
+ const name = parts.at(-1) ?? '';
1711
+ if (WORKSPACE_CONTEXT_PRIORITY_FILES.has(name))
1712
+ return true;
1713
+ const dot = name.lastIndexOf('.');
1714
+ if (dot < 0)
1715
+ return false;
1716
+ return WORKSPACE_CONTEXT_ALLOWED_EXTENSIONS.has(name.slice(dot).toLowerCase());
1717
+ }
1718
+ function numberWorkspaceContextLines(text) {
1719
+ return text.split(/\r?\n/).map((line, index) => {
1720
+ return `${String(index + 1).padStart(4, ' ')} | ${line}`;
1721
+ }).join('\n');
1722
+ }
1723
+ function splitLines(value) {
1724
+ return value.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
1725
+ }
1726
+ function uniqueStrings(values) {
1727
+ const seen = new Set();
1728
+ const out = [];
1729
+ for (const value of values) {
1730
+ const normalized = value.trim();
1731
+ if (!normalized || seen.has(normalized))
1732
+ continue;
1733
+ seen.add(normalized);
1734
+ out.push(normalized);
1735
+ }
1736
+ return out;
1737
+ }
1485
1738
  async function removeCleanGitWorktree(worktree) {
1486
1739
  try {
1487
1740
  await gitOutput(worktree.gitRoot, ['worktree', 'remove', '--force', worktree.path]);
@@ -2507,6 +2760,7 @@ function installWorkflowVmGlobals(context, globals) {
2507
2760
  ' define(globalThis, "agent", { value: (...values) => __host.agent(...values), writable: false, configurable: false });',
2508
2761
  ' define(globalThis, "parallel", { value: (...values) => __host.parallel(...values), writable: false, configurable: false });',
2509
2762
  ' define(globalThis, "pipeline", { value: (...values) => __host.pipeline(...values), writable: false, configurable: false });',
2763
+ ' define(globalThis, "workspaceContext", { value: (...values) => __host.workspaceContext(...values), writable: false, configurable: false });',
2510
2764
  ' define(globalThis, "phase", { value: (...values) => __host.phase(...values), writable: false, configurable: false });',
2511
2765
  ' define(globalThis, "log", { value: (...values) => __host.log(...values), writable: false, configurable: false });',
2512
2766
  ' define(globalThis, "workflow", { value: (...values) => __host.workflow(...values), writable: false, configurable: false });',
@@ -0,0 +1,56 @@
1
+ # Provenance Audit
2
+
3
+ Date: 2026-06-22
4
+
5
+ ## Scope
6
+
7
+ This audit checked:
8
+
9
+ - tracked repository files;
10
+ - generated npm package contents for `ultracode-for-codex@0.2.2`;
11
+ - the locally installed companion Codex skill.
12
+
13
+ Generated build output and package tarballs were checked as projections of the
14
+ tracked source. Dependency source trees were treated as third-party dependency
15
+ inputs, not project-authored code.
16
+
17
+ ## Result
18
+
19
+ Repository and package artifacts are clear for the Apache-2.0 license from an
20
+ artifact-provenance perspective.
21
+
22
+ License transition completed:
23
+
24
+ - Apache-2.0 `LICENSE` file is present;
25
+ - `package.json` and `package-lock.json` declare `Apache-2.0`;
26
+ - package version is prepared as `0.2.2` for the license-bearing patch release.
27
+
28
+ ## Evidence
29
+
30
+ - High-risk historical-source marker search: zero matches in tracked source,
31
+ generated package contents, and local companion skill after cleanup.
32
+ - Legacy API-project marker search: zero matches in tracked source, generated
33
+ package contents, and local companion skill after cleanup.
34
+ - Packaged runtime contents are limited to the CLI runtime, current docs,
35
+ settings, and companion skill.
36
+ - Production dependencies: none.
37
+ - Development dependencies: TypeScript and Node type packages only.
38
+ - Bundled third-party code: none.
39
+
40
+ Expected platform-control markers remain:
41
+
42
+ - provider environment variable names used by child-process environment
43
+ stripping and tests;
44
+ - Codex feature names used to disable unrelated child runtime features;
45
+ - npm registry and GitHub metadata URLs.
46
+
47
+ ## Remediation Completed
48
+
49
+ The local companion skill had stale local-only reference files that were not in
50
+ the package skill. Those local references were removed, and the local skill agent
51
+ metadata was synchronized with the packaged skill.
52
+
53
+ ## Residual Risk
54
+
55
+ This audit validates repository and package artifacts. It does not determine
56
+ external service contract compliance or replace legal review.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ultracode-for-codex",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "Run local Codex-backed workflows from a command-owned CLI runtime.",
5
5
  "keywords": [
6
6
  "codex",
@@ -17,7 +17,7 @@
17
17
  "type": "git",
18
18
  "url": "git+https://github.com/kangminlee-maker/ultracode-for-codex.git"
19
19
  },
20
- "license": "UNLICENSED",
20
+ "license": "Apache-2.0",
21
21
  "type": "module",
22
22
  "bin": {
23
23
  "ultracode-for-codex": "dist/cli.js"
@@ -41,6 +41,7 @@
41
41
  "skills/ultracode-for-codex/",
42
42
  "settings.json",
43
43
  "README.md",
44
+ "docs/provenance-audit.md",
44
45
  "docs/ultracode-p3a-journal-design.md",
45
46
  "docs/ultracode-p3b-resume-cache.md",
46
47
  "docs/ultracode-p3c-worktree-isolation.md"
@@ -61,7 +62,6 @@
61
62
  "typecheck": "tsc --noEmit -p tsconfig.json",
62
63
  "run": "npm run build && node dist/cli.js run --accept-llm-guide=v1"
63
64
  },
64
- "dependencies": {},
65
65
  "devDependencies": {
66
66
  "@types/node": "^22.0.0",
67
67
  "typescript": "^5.9.3"
@@ -35,7 +35,7 @@ For source-checkout validation before publish:
35
35
 
36
36
  ```bash
37
37
  npm run pack:ultracode-for-codex
38
- npm install --save-dev ./artifacts/ultracode-for-codex-0.2.0.tgz
38
+ npm install --save-dev ./artifacts/ultracode-for-codex-0.2.2.tgz
39
39
  ```
40
40
 
41
41
  CLI behavior:
@@ -58,6 +58,10 @@ CLI behavior:
58
58
 
59
59
  - Use Codex app-server over stdio as the production backend.
60
60
  - Keep direct provider credentials out of Codex child process environments.
61
+ - Codex subagents run against the requested workflow cwd and have bounded
62
+ read-only workspace tools for text file reads and directory listings.
63
+ - Built-in `code-review` injects deterministic workspace context and prioritizes
64
+ files explicitly mentioned in the prompt.
61
65
  - Keep workflow execution local and command-owned; settings default to OS
62
66
  background execution and `--execution attached` keeps the process connected
63
67
  until completion.