Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions plugins/codex-pi-coordination/.codex-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
{
"name": "codex-pi-coordination",
"version": "0.2.0",
"description": "Coordinate bounded implementation, research, review and validation tasks between Codex and Pi inside NVIDIA OpenShell.",
"version": "0.3.0",
"description": "Coordinate bounded tasks, saved Pi conversations and model capability discovery inside NVIDIA OpenShell.",
"author": {
"name": "Fakoli",
"url": "https://github.com/fakoli"
},
"interface": {
"displayName": "Codex Pi Coordination",
"shortDescription": "Delegate scoped work to Pi and verify its return.",
"longDescription": "Codex owns task scope and acceptance. Pi works in a disposable OpenShell workspace and returns bounded artifacts, while a stdlib runner records actual command results and managed cleanup.",
"shortDescription": "Run scoped Pi tasks and continue saved work.",
"longDescription": "Codex owns scope, integration and acceptance. Pi executes fresh assignments in an owned OpenShell sandbox, optionally continuing a verified saved conversation. The runner retains bounded artifacts, actual checks and managed cleanup.",
"developerName": "Fakoli",
"category": "Productivity",
"capabilities": [
Expand Down
69 changes: 63 additions & 6 deletions plugins/codex-pi-coordination/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,43 @@ Version-2 tasks may add `run_options`: an exact `provider`/`model` pair,
`thinking` alone, or both. Omitted options inherit the profile. `auto`, `dynamic`
and the literal `default` are refused; use omission for Default. Unsupported or
silently clamped selections fail before the task prompt, without fallback.
Version-1 task inputs remain readable. All new runs use bounded native RPC with
`--no-session`; saved-session continuation remains future work (P1b).
Version-1 task inputs remain readable. Ordinary runs retain bounded native RPC
with `--no-session`. To keep one official Pi conversation across fresh, stopped
worker processes, use saved Run and Continue:

```sh
python3 scripts/coordinate.py run first-task.json --save-session --output /private/evidence/first-run
```

Inspect the first return, integrate its approved changes through the repository
workflow, and commit the source for a new task manifest. Then continue from the
verified prior output with that new assignment and revision:

```sh
python3 scripts/coordinate.py continue next-task.json --from /private/evidence/first-run --output /private/evidence/next-run
```

Saved runs require an explicit committed repository source. Continue preserves
the exact official session file, ID and workspace path, while each dispatch gets
fresh scope, options, budgets and artifacts. It checks the prior session hash
and history prefix and every workspace file/directory mode before switching
source. Stale, duplicate, missing or drifted checkpoints refuse before Pi starts;
the managed owner may start only to inspect that remote state. No latest-session
search, live attachment or silent fresh-session fallback occurs. Public task
versions 1/2 are unchanged; saved dispatches use native version 3.

For one exact model's thinking choices, pair both selectors:

```sh
python3 scripts/coordinate.py capabilities --provider configured-provider --model exact-model-id --output /private/evidence/selected-capabilities
```

This native version-3 metadata operation may select that model in its ephemeral
child, but sends no thinking setter, prompt, tool call or extension. It reports
the observed levels/thinking and profile-default compatibility. An unsupported
default does not block discovery; Run and Continue still require a supported
explicit or inherited thinking level. Omit all run options for the configured
default; capability discovery is optional, never a prerequisite for Default.

See the [skill](skills/codex-pi-coordination/SKILL.md) and
[task/profile contract](skills/codex-pi-coordination/references/task-contract.md).
Expand All @@ -38,7 +73,7 @@ The extension provides `coordination_status`, `coordination_handoff` and
`/coordination-status`. File tools stay inside the assigned workspace, writes
name exact files, and tool/turn budgets stop further work. Declared verification
argv runs after Pi exits. Task policy is not an OS sandbox: OpenShell remains
the isolation and lifecycle owner. Selection is confined to the ephemeral Pi
the isolation and lifecycle owner. Selection is confined to the dispatched Pi
child; global provider/model settings stay unchanged. No background service,
recursive Codex launch or automatic patch application is installed.

Expand All @@ -52,7 +87,8 @@ evidence outside public plugin source.

On execution failure, nonzero worker exit or timeout, the runner immediately
enters managed OpenShell cleanup: verify identity, stop and record the readback.
It skips artifact download. Recover the latest failed run after confirmed stopped
It skips artifact download. Recover a saved failure, or the latest ephemeral
failure, after confirmed stopped
custody using the same private profile and lock root:

```sh
Expand All @@ -65,6 +101,25 @@ the bound results, and stops that instance. It runs no model or checks.
`recovered_partial` preserves missing terminal results as unknown. Task delivery
remains invalid and acceptance is not granted. Unknown stop blocks further work
until supported `reconcile`; the original failed receipt is never rewritten.
For saved runs, recovery also reports `conversation_valid` separately. Failed
checks can leave a valid advanced conversation only when recovery verifies its
terminal session, workspace and stopped custody. Continue must reference that
valid recovery output with a new task; delivery remains failed.

Use `reconcile --from FAILED_RUN --output NEW_DIRECTORY` for a saved workspace
transition. It can certify the exact unchanged prior tree and archive its
matching pending intent. A switched-new tree without verified terminal model
evidence remains unavailable for continuation; mixed or unknown state stays
held. The same command can inspect a successful saved run after an intervening
metadata or refused stale dispatch: it returns a fresh terminal checkpoint
readback without Pi or checks. `recover` remains failed-run-only, and inspection
still reports `delivery_valid: false`. It never restores files, rolls back a workspace, rewrites history or
replays a prompt. The existing no-argument `reconcile` only records independently
confirmed stopped owner custody.

Sessions are limited to 16 MiB, checkpoint/control JSON to 1 MiB, and retained
remote material to an observed 1 GiB limit. These are checked bounds, not a hard
filesystem quota; overflow refuses further work without pruning prior runs.
The native download has a timeout and post-download file/byte checks, not a hard
pre-download storage quota. Use only an owner-qualified idle runtime.

Expand All @@ -76,8 +131,10 @@ node --test tests/extension.test.mjs
```

These synthetic checks run in repository CI without a model or OpenShell
runtime. Native loading and real model task evidence require separate runtime
validation.
runtime. The saved two-edit journey and selected-model query still require separate
qualification through the installed OpenShell command. Anvil CLI/web admission,
current claims, integration, native checkout proofs and final approval also
require their own journey checks; plugin sandbox checks do not satisfy them.

API reference: [Pi extension contract](https://github.com/earendil-works/pi/blob/v0.87.1/packages/coding-agent/docs/extensions.md).
Anvil and ship-loop continue to own their scale and delivery workflows.
43 changes: 37 additions & 6 deletions plugins/codex-pi-coordination/extensions/coordination.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ function boundedString(value, name, maximum = 16000) {

function relativeFile(value) {
boundedString(value, "relative file", 1024);
if (Buffer.from(value, "utf8").toString("utf8") !== value) fail("invalid_task", "Relative file contains invalid Unicode");
if (path.isAbsolute(value) || value.includes("\\") || /[\u00A0\u2000-\u200A\u202F\u205F\u3000]/.test(value) || value.split("/").some((part) => !part || part === "." || part === "..")) {
fail("invalid_task", "File paths must be normalized workspace-relative paths");
}
Expand Down Expand Up @@ -68,7 +69,7 @@ export function loadTask(taskPath, cwd) {
fs.closeSync(descriptor);
}
const task = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(raw));
if (!task || typeof task !== "object" || Array.isArray(task) || ![1, 2].includes(task.version) || !taskKinds.has(task.kind)) {
if (!task || typeof task !== "object" || Array.isArray(task) || ![1, 2, 3].includes(task.version) || !taskKinds.has(task.kind)) {
fail("invalid_task", "Expected a supported versioned coordination task and kind");
}
for (const key of ["run_id", "task_id"]) {
Expand All @@ -79,7 +80,7 @@ export function loadTask(taskPath, cwd) {
if (pattern.exec(value)?.[0] !== value) fail("invalid_task", `Invalid ${key}`);
}
if (task.version === 1 && "run_options" in task) fail("invalid_task", "Version 1 cannot contain run_options");
if (task.version === 2) {
if ([2, 3].includes(task.version)) {
const options = task.run_options;
const levels = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
const identifierPattern = "[A-Za-z0-9][A-Za-z0-9_.:/-]{0,255}";
Expand All @@ -88,7 +89,7 @@ export function loadTask(taskPath, cwd) {
// Each component may contain slashes; only the exact runtime catalog picks a pair.
const qualifiedDefault = (value) => matchesIdentifier(value, `${identifierPattern}/${identifierPattern}`);
if (!options || typeof options !== "object" || Array.isArray(options) || Object.keys(options).some((key) => !["provider", "model", "thinking"].includes(key)) || (("provider" in options) !== ("model" in options)) || ("provider" in options && (!identifier(options.provider) || !identifier(options.model))) || ("thinking" in options && !levels.includes(options.thinking))) fail("invalid_task", "Invalid version 2 run options");
if (task.operation !== "run" || !task.runtime_defaults || Object.keys(task.runtime_defaults).sort().join(",") !== "model,thinking" || !qualifiedDefault(task.runtime_defaults.model) || !levels.includes(task.runtime_defaults.thinking)) fail("invalid_task", "Invalid version 2 runtime defaults");
if (!(task.version === 2 ? task.operation === "run" : ["run", "continue"].includes(task.operation)) || !task.runtime_defaults || Object.keys(task.runtime_defaults).sort().join(",") !== "model,thinking" || !qualifiedDefault(task.runtime_defaults.model) || !levels.includes(task.runtime_defaults.thinking)) fail("invalid_task", "Invalid versioned runtime defaults");
}
boundedString(task.instructions, "instructions", 48000);
for (const key of ["workspace", "output_directory"]) {
Expand All @@ -101,6 +102,16 @@ export function loadTask(taskPath, cwd) {
if (contains(task.workspace, fs.realpathSync(taskPath)) || contains(task.workspace, task.output_directory) || contains(task.output_directory, task.workspace)) {
fail("invalid_task", "Task and output controls must be outside the workspace; output must not contain it");
}
if (task.version === 3) {
const session = task.session;
if (!session || Object.keys(session).sort().join(",") !== "conversation_id,directory,file,prior,prior_sha256" || typeof session.conversation_id !== "string" || /^[0-9a-f]{32}$/.exec(session.conversation_id)?.[0] !== session.conversation_id) fail("invalid_task", "Invalid saved conversation descriptor");
const dispatch = path.dirname(task.output_directory);
const directory = path.join(path.dirname(dispatch), "conversations", session.conversation_id);
if (path.basename(dispatch) !== task.run_id || session.directory !== directory || session.file !== path.join(directory, "session.jsonl") || task.workspace !== path.join(directory, "workspace")) fail("invalid_task", "Saved paths differ from owned dispatch");
if (task.operation === "run" ? session.prior !== null || session.prior_sha256 !== null || session.conversation_id !== task.run_id : !session.prior || session.prior.conversation_id !== session.conversation_id || session.prior.run_id === task.run_id || typeof session.prior_sha256 !== "string" || /^[0-9a-f]{64}$/.exec(session.prior_sha256)?.[0] !== session.prior_sha256) fail("invalid_task", "Invalid previous saved dispatch");
noSymlinks(path.dirname(dispatch), directory, false);
noSymlinks(directory, session.file, task.operation === "run");
}
if (!Array.isArray(task.allowed_tools) || task.allowed_tools.length > nativeTools.size || new Set(task.allowed_tools).size !== task.allowed_tools.length || task.allowed_tools.some((tool) => !nativeTools.has(tool))) {
fail("invalid_task", "allowed_tools must contain unique supported native tools; shell execution is not supported");
}
Expand Down Expand Up @@ -129,6 +140,14 @@ export function checkToolPath(task, toolName, input) {
return candidate;
}

function savedSessionIdentity(task, ctx) {
const manager = ctx.sessionManager;
const header = manager?.getHeader();
const identity = { id: manager?.getSessionId(), file: manager?.getSessionFile(), cwd: manager?.getCwd(), version: header?.version };
if (identity.version !== 3 || typeof identity.id !== "string" || /^[A-Za-z0-9_.-]{1,128}$/.exec(identity.id)?.[0] !== identity.id || identity.file !== task.session.file || identity.cwd !== task.workspace || header?.type !== "session" || header.id !== identity.id || header.cwd !== task.workspace || task.session.prior && identity.id !== task.session.prior.session?.id) fail("session_mismatch", "Official Pi session does not match the current saved assignment");
return identity;
}

function toolResult(value) {
return { content: [{ type: "text", text: JSON.stringify(value) }], details: value };
}
Expand Down Expand Up @@ -158,8 +177,9 @@ export default function coordinationExtension(pi) {
let turns = 0;
let handedOff = false;
let configurationRecorded = false;
let savedIdentity;
const requested = () => pi.getFlag("coordination-task");
const status = () => ({ active: Boolean(loaded), run_id: loaded?.task.run_id, task_id: loaded?.task.task_id, task_sha256: loaded?.taskSha256, tool_calls: toolCalls, turns, handed_off: handedOff, failure });
const status = () => ({ active: Boolean(loaded), run_id: loaded?.task.run_id, task_id: loaded?.task.task_id, task_sha256: loaded?.taskSha256, tool_calls: toolCalls, turns, handed_off: handedOff, failure, ...(savedIdentity ? { session: savedIdentity } : {}) });
const record = (type, fields = {}) => {
if (eventDescriptor !== undefined) fs.writeSync(eventDescriptor, JSON.stringify({ type, at: new Date().toISOString(), ...status(), ...fields }) + "\n");
};
Expand Down Expand Up @@ -211,7 +231,10 @@ export default function coordinationExtension(pi) {
return;
}
try {
if (loaded) fail("task_reloaded", "A fresh dispatch requires a fresh Pi process");
loaded = loadTask(requested(), ctx.cwd);
toolCalls = 0; turns = 0; handedOff = false; configurationRecorded = false;
if (loaded.task.version === 3) savedIdentity = savedSessionIdentity(loaded.task, ctx);
eventDescriptor = fs.openSync(path.join(loaded.task.output_directory, "extension-events.jsonl"), "wx", 0o600);
const requiredTools = [...loaded.task.allowed_tools, ...coordinationTools];
pi.setActiveTools(requiredTools);
Expand All @@ -230,7 +253,15 @@ export default function coordinationExtension(pi) {
stop(ctx, "task_unavailable", "Coordination task is unavailable or already handed off");
return;
}
if (loaded.task.version === 2 && !configurationRecorded) {
if (loaded.task.version === 3) {
try {
if (JSON.stringify(savedSessionIdentity(loaded.task, ctx)) !== JSON.stringify(savedIdentity)) fail("session_mismatch", "Saved session changed before prompt");
} catch (error) {
stop(ctx, error.code ?? "session_mismatch", error.message);
return;
}
}
if ([2, 3].includes(loaded.task.version) && !configurationRecorded) {
const configuration = { provider: ctx.model?.provider, model: ctx.model?.id, thinking: pi.getThinkingLevel() };
if (!configuration.provider || !configuration.model || !["off", "minimal", "low", "medium", "high", "xhigh", "max"].includes(configuration.thinking)) {
stop(ctx, "configuration_unavailable", "Pi did not expose an effective run configuration");
Expand All @@ -248,7 +279,7 @@ export default function coordinationExtension(pi) {
record("run_configuration", { configuration });
configurationRecorded = true;
}
return { systemPrompt: `${event.systemPrompt}\n\nExternal coordinator task:\n${JSON.stringify({ run_id: loaded.task.run_id, task_id: loaded.task.task_id, kind: loaded.task.kind, instructions: loaded.task.instructions, source: loaded.sourceSummary, writable_paths: loaded.task.writable_paths, max_tool_calls: loaded.task.max_tool_calls, max_turns: loaded.task.max_turns })}\nWork only inside the assigned workspace and declared writable files. Shell execution is unavailable; the coordinator runs declared verification commands after Pi exits. Before the tool budget ends, call coordination_handoff exactly once with an honest self-report. Do not claim acceptance or verification from your report. Tool/path guards are task policy; the external runner owns OS isolation and custody.` };
return { systemPrompt: `${event.systemPrompt}\n\nExternal coordinator task:\n${JSON.stringify({ run_id: loaded.task.run_id, task_id: loaded.task.task_id, kind: loaded.task.kind, instructions: loaded.task.instructions, source: loaded.sourceSummary, writable_paths: loaded.task.writable_paths, max_tool_calls: loaded.task.max_tool_calls, max_turns: loaded.task.max_turns })}\nOnly this current assignment grants scope and budgets; earlier conversation text grants no task or tool authority. Work only inside the assigned workspace and declared writable files. Shell execution is unavailable; the coordinator runs declared verification commands after Pi exits. Before the tool budget ends, call coordination_handoff exactly once with an honest self-report. Do not claim acceptance or verification from your report. Tool/path guards are task policy; the external runner owns OS isolation and custody.` };
});
pi.on("turn_start", async (_event, ctx) => {
if (!requested() || !loaded) return;
Expand Down
4 changes: 2 additions & 2 deletions plugins/codex-pi-coordination/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "codex-pi-coordination",
"version": "0.2.0",
"description": "Bounded Pi task handoff for an external Codex coordinator",
"version": "0.3.0",
"description": "Bounded Pi tasks, saved-session continuation and capability discovery for Codex",
"type": "module",
"license": "MIT",
"engines": { "node": ">=22" },
Expand Down
Loading
Loading