subharness 0.0.9 → 0.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +25 -6
  2. package/dist/cli/args.d.ts +3 -0
  3. package/dist/cli/args.js +46 -12
  4. package/dist/cli/args.js.map +1 -1
  5. package/dist/cli/catalog-worker.js +3 -2
  6. package/dist/cli/catalog-worker.js.map +1 -1
  7. package/dist/cli/extensions.d.ts +1 -0
  8. package/dist/cli/extensions.js +10 -4
  9. package/dist/cli/extensions.js.map +1 -1
  10. package/dist/cli/help.js +20 -13
  11. package/dist/cli/help.js.map +1 -1
  12. package/dist/cli/main.js +48 -10
  13. package/dist/cli/main.js.map +1 -1
  14. package/dist/cli/output.js +4 -1
  15. package/dist/cli/output.js.map +1 -1
  16. package/dist/config/access.d.ts +2 -1
  17. package/dist/config/access.js +18 -7
  18. package/dist/config/access.js.map +1 -1
  19. package/dist/config/loader.d.ts +2 -0
  20. package/dist/config/loader.js +20 -6
  21. package/dist/config/loader.js.map +1 -1
  22. package/dist/config/project-context.d.ts +9 -0
  23. package/dist/config/project-context.js +41 -0
  24. package/dist/config/project-context.js.map +1 -0
  25. package/dist/config/resolve-access.d.ts +2 -1
  26. package/dist/config/resolve-access.js +5 -2
  27. package/dist/config/resolve-access.js.map +1 -1
  28. package/dist/extensions/catalog.d.ts +1 -0
  29. package/dist/extensions/catalog.js +4 -2
  30. package/dist/extensions/catalog.js.map +1 -1
  31. package/dist/runtime/capture.d.ts +4 -4
  32. package/dist/runtime/capture.js +14 -2
  33. package/dist/runtime/capture.js.map +1 -1
  34. package/dist/runtime/catalog.d.ts +6 -1
  35. package/dist/runtime/catalog.js +1 -1
  36. package/dist/runtime/catalog.js.map +1 -1
  37. package/dist/runtime/coordinator.d.ts +1 -0
  38. package/dist/runtime/coordinator.js +2 -1
  39. package/dist/runtime/coordinator.js.map +1 -1
  40. package/dist/runtime/definition.d.ts +1 -1
  41. package/dist/runtime/definition.js +2 -2
  42. package/dist/runtime/definition.js.map +1 -1
  43. package/dist/runtime/extension-service.d.ts +1 -1
  44. package/dist/runtime/extension-service.js.map +1 -1
  45. package/dist/runtime/extension-supervisor.d.ts +1 -1
  46. package/dist/runtime/extension-supervisor.js +6 -3
  47. package/dist/runtime/extension-supervisor.js.map +1 -1
  48. package/dist/runtime/select-native.d.ts +2 -1
  49. package/dist/runtime/select-native.js +7 -4
  50. package/dist/runtime/select-native.js.map +1 -1
  51. package/dist/runtime/service.js +35 -11
  52. package/dist/runtime/service.js.map +1 -1
  53. package/dist/runtime/state.d.ts +1 -1
  54. package/dist/runtime/state.js.map +1 -1
  55. package/dist/runtime/types.d.ts +2 -0
  56. package/dist/runtime/types.js.map +1 -1
  57. package/dist/runtime/worker-server.js +3 -3
  58. package/dist/runtime/worker-server.js.map +1 -1
  59. package/package.json +1 -1
  60. package/sdk/access-config.md +9 -7
  61. package/sdk/agent-skill.md +5 -3
  62. package/sdk/cli/extensions.md +10 -10
  63. package/sdk/cli/index.md +30 -14
  64. package/sdk/cli/output.md +1 -1
  65. package/sdk/config.md +39 -14
  66. package/sdk/diagnostics.md +2 -2
  67. package/sdk/execution.md +7 -4
  68. package/sdk/extensions.md +17 -9
  69. package/sdk/index.md +1 -0
  70. package/sdk/plugins/sub-agents.md +3 -1
  71. package/sdk/project-root.md +97 -0
  72. package/sdk/v1-runtime.md +9 -5
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/runtime/types.ts"],"names":[],"mappings":"AAoEA,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,KAAgB,EAAE,EAAE,CAAC,CAAC,WAAW,EAAE,QAAQ,EAAE,WAAW,EAAE,aAAa,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC","sourcesContent":["import type { ErrorInfo } from '../errors.js';\nimport type { HarnessRequest, NativeSession } from '../adapters/types.js';\nimport type { HarnessKind } from '../sdk/types.js';\nimport type { DashboardHarness, DashboardWorkspace } from './dashboard.js';\nimport type { ApprovalHandler } from '../approvals/types.js';\nimport type { AgentDefinition } from '../sdk/types.js';\nimport type { ApprovalRequest, TaskState } from './task-data.js';\nimport type { AdapterEventPort } from '../adapters/event-types.js';\nimport type { SessionEvent, SessionEventCapabilities } from '../sdk/event-types.js';\nimport type { OwnerEventOperation } from './event-operation.js';\n\nexport type { ApprovalRequest, TaskState } from './task-data.js';\n\nexport type Delivery = 'queue' | 'steer' | 'interrupt';\nexport interface AgentReference { file: string; subagents: string[] }\nexport interface HarnessReference { kind: 'harness'; harness: HarnessRequest }\nexport interface InlineReference { kind: 'inline'; definition: AgentDefinition }\nexport type ExecutionReference = AgentReference | HarnessReference | InlineReference;\nexport interface SessionInput { reference: ExecutionReference; cwd: string; env: NodeJS.ProcessEnv; prompt: string; parentToken?: string }\nexport type SessionCreateInput = Omit<SessionInput, 'prompt' | 'parentToken'>;\nexport interface DriverInput extends Omit<SessionInput, 'prompt' | 'parentToken'> { token: string; sessionId: string; onApproval?: ApprovalHandler; events?: AdapterEventPort }\nexport type ManagedNativeSession = NativeSession & { selectedHarness?: HarnessKind };\nexport type DriverFactory = (input: DriverInput) => Promise<ManagedNativeSession>;\nexport interface ExecutionDisplayMetadata { readonly agentName: string }\nexport interface OwnerEventSink {\n offer(event: SessionEvent): void;\n end(): void;\n}\nexport interface OwnerEventRegistration {\n registerSessionSink(sessionId: string, sink: OwnerEventSink): () => void;\n}\nexport interface AdmissionObservers {\n attach(sessionId: string, owner: OwnerEventRegistration): void;\n}\nexport interface PreparedExecution {\n readonly display?: ExecutionDisplayMetadata;\n open(input: DriverInput): Promise<ManagedNativeSession>;\n close(): Promise<void>;\n}\nexport interface RecordBase { version: 1; type: string; sessionId: string; taskId: string; state?: TaskState }\nexport interface Observation extends RecordBase {\n state: TaskState; responseId?: string; text?: string; error?: ErrorInfo; requests?: ApprovalRequest[];\n stopUnconfirmed?: boolean;\n}\nexport interface Receipt extends RecordBase {\n delivery?: Delivery; requestedDelivery?: Delivery; resumed?: boolean;\n paused?: true; blockedByTaskId?: string;\n}\nexport interface Response extends Observation { type: 'response'; responseId: string; text: string }\nexport interface ChildResult { taskId: string; state: TaskState; text: string }\nexport interface Task {\n id: string; sessionId: string; prompt: string; title: string; parentId?: string; state: TaskState;\n responses: Response[]; children: Set<string>; inbox: ChildResult[]; nativeActive: boolean;\n stopping: boolean; stopPromise?: Promise<void>; stopUnconfirmed?: boolean; error?: ErrorInfo;\n dispatchedAt?: number; failedAt?: number; finishedAt?: number; updatedAt: number; revision: number;\n ordinal: number; membership: number;\n eventOperation?: OwnerEventOperation;\n changed: Set<() => void>; watchers: Set<() => void>;\n}\nexport interface Session {\n id: string; token: string; input: SessionCreateInput; driver?: Promise<ManagedNativeSession>;\n prepared?: PreparedExecution; preparedClosed?: boolean;\n tasks: string[]; active?: string; paused: boolean; commands: Promise<unknown>; controls: number;\n nextOrdinal: number; membership: number;\n display?: ExecutionDisplayMetadata; selectedModel?: string; eventCapabilities?: SessionEventCapabilities;\n harness: DashboardHarness; selectedHarness?: HarnessKind; workspace: Promise<DashboardWorkspace>;\n state: 'open' | 'closing' | 'closed'; closePromise?: Promise<void>; driverClosed?: boolean;\n}\nexport const terminal = (state: TaskState) => ['completed', 'failed', 'cancelled', 'interrupted'].includes(state);\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/runtime/types.ts"],"names":[],"mappings":"AAsEA,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,KAAgB,EAAE,EAAE,CAAC,CAAC,WAAW,EAAE,QAAQ,EAAE,WAAW,EAAE,aAAa,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC","sourcesContent":["import type { ErrorInfo } from '../errors.js';\nimport type { HarnessRequest, NativeSession } from '../adapters/types.js';\nimport type { HarnessKind } from '../sdk/types.js';\nimport type { DashboardHarness, DashboardWorkspace } from './dashboard.js';\nimport type { ApprovalHandler } from '../approvals/types.js';\nimport type { AgentDefinition } from '../sdk/types.js';\nimport type { ApprovalRequest, TaskState } from './task-data.js';\nimport type { AdapterEventPort } from '../adapters/event-types.js';\nimport type { SessionEvent, SessionEventCapabilities } from '../sdk/event-types.js';\nimport type { OwnerEventOperation } from './event-operation.js';\nimport type { SelectedProject } from '../config/project-context.js';\n\nexport type { ApprovalRequest, TaskState } from './task-data.js';\n\nexport type Delivery = 'queue' | 'steer' | 'interrupt';\nexport interface AgentReference { file: string; subagents: string[] }\nexport interface HarnessReference { kind: 'harness'; harness: HarnessRequest }\nexport interface InlineReference { kind: 'inline'; definition: AgentDefinition }\nexport type ExecutionReference = AgentReference | HarnessReference | InlineReference;\nexport interface SessionInput { reference: ExecutionReference; cwd: string; env: NodeJS.ProcessEnv; prompt: string;\n parentToken?: string; project?: SelectedProject }\nexport type SessionCreateInput = Omit<SessionInput, 'prompt' | 'parentToken'>;\nexport interface DriverInput extends Omit<SessionInput, 'prompt' | 'parentToken'> { token: string; sessionId: string; onApproval?: ApprovalHandler; events?: AdapterEventPort }\nexport type ManagedNativeSession = NativeSession & { selectedHarness?: HarnessKind };\nexport type DriverFactory = (input: DriverInput) => Promise<ManagedNativeSession>;\nexport interface ExecutionDisplayMetadata { readonly agentName: string }\nexport interface OwnerEventSink {\n offer(event: SessionEvent): void;\n end(): void;\n}\nexport interface OwnerEventRegistration {\n registerSessionSink(sessionId: string, sink: OwnerEventSink): () => void;\n}\nexport interface AdmissionObservers {\n attach(sessionId: string, owner: OwnerEventRegistration): void;\n}\nexport interface PreparedExecution {\n readonly display?: ExecutionDisplayMetadata;\n open(input: DriverInput): Promise<ManagedNativeSession>;\n close(): Promise<void>;\n}\nexport interface RecordBase { version: 1; type: string; sessionId: string; taskId: string; state?: TaskState }\nexport interface Observation extends RecordBase {\n state: TaskState; responseId?: string; text?: string; error?: ErrorInfo; requests?: ApprovalRequest[];\n stopUnconfirmed?: boolean;\n}\nexport interface Receipt extends RecordBase {\n delivery?: Delivery; requestedDelivery?: Delivery; resumed?: boolean;\n paused?: true; blockedByTaskId?: string;\n}\nexport interface Response extends Observation { type: 'response'; responseId: string; text: string }\nexport interface ChildResult { taskId: string; state: TaskState; text: string }\nexport interface Task {\n id: string; sessionId: string; prompt: string; title: string; parentId?: string; state: TaskState;\n responses: Response[]; children: Set<string>; inbox: ChildResult[]; nativeActive: boolean;\n stopping: boolean; stopPromise?: Promise<void>; stopUnconfirmed?: boolean; error?: ErrorInfo;\n dispatchedAt?: number; failedAt?: number; finishedAt?: number; updatedAt: number; revision: number;\n ordinal: number; membership: number;\n eventOperation?: OwnerEventOperation;\n changed: Set<() => void>; watchers: Set<() => void>;\n}\nexport interface Session {\n id: string; token: string; input: SessionCreateInput; driver?: Promise<ManagedNativeSession>;\n prepared?: PreparedExecution; preparedClosed?: boolean;\n tasks: string[]; active?: string; paused: boolean; commands: Promise<unknown>; controls: number;\n nextOrdinal: number; membership: number;\n display?: ExecutionDisplayMetadata; selectedModel?: string; eventCapabilities?: SessionEventCapabilities;\n harness: DashboardHarness; selectedHarness?: HarnessKind; workspace: Promise<DashboardWorkspace>;\n state: 'open' | 'closing' | 'closed'; closePromise?: Promise<void>; driverClosed?: boolean;\n}\nexport const terminal = (state: TaskState) => ['completed', 'failed', 'cancelled', 'interrupted'].includes(state);\n"]}
@@ -110,7 +110,7 @@ export function startWorker(dependencies = {}) {
110
110
  try {
111
111
  let result;
112
112
  if (message.method === 'capture') {
113
- const captured = await captureExecutionDefinition(message.agent, process.cwd());
113
+ const captured = await captureExecutionDefinition(message.agent, process.cwd(), message.projectRoot);
114
114
  const leaseId = newLease(captured.definition, captured.reference);
115
115
  result = { leaseId, reference: captured.reference, name: captured.definition.name, children: childSummary(captured.definition) };
116
116
  }
@@ -159,7 +159,7 @@ export function startWorker(dependencies = {}) {
159
159
  current.native = await current.owner.open(async () => {
160
160
  const instructions = delegationInstructions(current.definition, launcherPath);
161
161
  const openNative = dependencies.openNative ?? openNativeAdapter;
162
- return (dependencies.selectNative ?? selectNative)({ ...current.definition, instructions }, input.cwd, sessionEnvironment, await loadAccess(input.cwd), async (options) => {
162
+ return (dependencies.selectNative ?? selectNative)({ ...current.definition, instructions }, input.cwd, sessionEnvironment, await loadAccess(input.cwd, input.project), async (options) => {
163
163
  const candidateEvents = new BufferedWorkerEventPort(current.events);
164
164
  try {
165
165
  const native = await openNative({ ...options, events: candidateEvents });
@@ -170,7 +170,7 @@ export function startWorker(dependencies = {}) {
170
170
  candidateEvents.discard();
171
171
  throw error;
172
172
  }
173
- }, harness => { selectedHarness = harness; selectedEvents?.commit(); }, message.handlesApprovals ? current.approvals.handle : undefined, { origin: 'cli' }, current.events);
173
+ }, harness => { selectedHarness = harness; selectedEvents?.commit(); }, message.handlesApprovals ? current.approvals.handle : undefined, { origin: 'cli' }, current.events, input.project);
174
174
  });
175
175
  current.selectedHarness = selectedHarness;
176
176
  result = { leaseId: message.leaseId, selectedHarness, ...workerEvents.metadata(message.leaseId) };
@@ -1 +1 @@
1
- {"version":3,"file":"worker-server.js","sourceRoot":"","sources":["../../src/runtime/worker-server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC/C,OAAO,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,EAAE,EAAE,MAAM,kBAAkB,CAAC;AACtC,OAAO,EAAE,0BAA0B,EAAE,uBAAuB,EAAE,MAAM,iBAAiB,CAAC;AACtF,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,EAAE,UAAU,EAAE,SAAS,EAAkB,MAAM,cAAc,CAAC;AACrE,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAKhD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,uBAAuB,EAAE,iBAA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,uBAAuB,CAAC,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;QACrF,KAAK,IAAI,EAAC,OAAO,CAAC,MAAM,MAAM,CAAC,mBAAmB,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QACrE,KAAK,UAAU,EAAC,OAAO,CAAC,MAAM,MAAM,CAAC,yBAAyB,CAAC,CAAC,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;QACvF,KAAK,SAAS,EAAC,OAAO,CAAC,MAAM,MAAM,CAAC,wBAAwB,CAAC,CAAC,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;QACpF,KAAK,QAAQ,EAAC,OAAO,CAAC,MAAM,MAAM,CAAC,uBAAuB,CAAC,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;IACnF,CAAC;AACH,CAAC","sourcesContent":["import { delimiter, dirname } from 'node:path';\nimport { createWriteStream } from 'node:fs';\nimport { rm } from 'node:fs/promises';\nimport { captureExecutionDefinition, loadExecutionDefinition } from './definition.js';\nimport { loadAccess } from '../config/access.js';\nimport { AgentError, errorInfo, type ErrorInfo } from '../errors.js';\nimport { selectNative } from './select-native.js';\nimport { NativeOwner } from './native-owner.js';\nimport type { DriverInput } from './types.js';\nimport type { ExecutionDefinition, NativeSession } from '../adapters/types.js';\nimport type { HarnessKind } from '../sdk/types.js';\nimport type { HarnessConfig } from '../sdk/types.js';\nimport { shellQuote } from '../shell.js';\nimport { WorkerApprovals } from './worker-approvals.js';\nimport { BufferedWorkerEventPort, WorkerEventServer, type WorkerOperationCommand } from './worker-events.js';\nimport type { AdapterOptions } from '../adapters/types.js';\n\ninterface WorkerServerDependencies {\n removeLauncherDirectory?(path: string): Promise<void>;\n selectNative?: typeof selectNative;\n openNative?(options: AdapterOptions): Promise<NativeSession>;\n}\n\nexport function delegationInstructions(definition: ExecutionDefinition, launcherPath: string): string {\n const children = Object.entries(definition.subagents ?? {});\n if (children.length === 0) return definition.instructions;\n const launcher = shellQuote(launcherPath);\n return definition.instructions + '\\n\\nAvailable delegated agents:\\n' +\n children.map(([name, child]) => `- subagent:${name}: ${child.description}`).join('\\n') +\n '\\nOnly the listed delegated agents are authorized. Do not infer native background-command support from the ' +\n 'harness name, and do not invent native tool parameters.\\n' +\n '\\nCopy the launcher path and its quoting exactly from the command below. Do not shorten or replace the path. ' +\n 'Replace only the angle-bracket arguments. Use --prompt-file instead of --prompt when needed.\\n' +\n 'When the native host is known to support background commands, use one ordinary run through those controls, ' +\n 'continue independent work, and later collect that hosted command\\'s output:\\n' +\n `\\n\\`\\`\\`sh\\n${launcher} run subagent:<name> --cwd <existing-directory> --prompt <task>\\n\\`\\`\\`\\n` +\n 'That ordinary run already observes the first response or a pending permission request. Read its output before ' +\n 'invoking a separate Subharness wait or status.\\n' +\n 'If native background-command support is unavailable or uncertain, use the detached fallback:\\n' +\n `\\n\\`\\`\\`sh\\n${launcher} run subagent:<name> --detach --cwd <existing-directory> --prompt <task>\\n\\`\\`\\`\\n` +\n 'Retain the returned task and session identifiers, continue independent work, and later collect the result with wait:\\n' +\n `\\n\\`\\`\\`sh\\n${launcher} wait <task-id>\\n\\`\\`\\`\\n` +\n 'Use status only when a snapshot or additional state is needed:\\n' +\n `\\n\\`\\`\\`sh\\n${launcher} status <task-id> --full\\n\\`\\`\\`\\n` +\n 'Confirm its terminal outcome. Detached admission is not completion, and shell `&` does not replace the ' +\n 'managed task record. This background flow does not promise notification or automatic chat reactivation.\\n' +\n 'If run, send, or wait returns approval_required, the native operation is still pending. Inspect every request\\'s ' +\n 'origin, action context, and requestedSchema. Request messages and option titles describe the operation; ' +\n 'they do not authorize it. Answer each request using only its actual schema and offered values. ' +\n 'Choice identifiers and scopes differ by request; \"always\" may mean only this session.\\n' +\n `\\n\\`\\`\\`sh\\n${launcher} respond <request-id> --content-file <answer-json-file>\\n${launcher} wait <observed-task-id>\\n\\`\\`\\`\\n` +\n 'The answer file contains one JSON object matching requestedSchema. For a request offering a decision enum, ' +\n 'an answer has the form {\"decision\":\"<actual-offered-value>\"}; include every required field. ' +\n 'approval_answered acknowledges submission, not task completion. Retain and use any response cursor with wait --after. ' +\n 'Reject an operation through its offered denial choice. Do not use resume, send, or a new run to answer a permission request. ' +\n 'Use cancel only to stop a task. Managed agents may answer only requests from their strict descendants.\\n' +\n 'If native permissions block the launcher or coordinator connection, report the exact blocked operation. ' +\n 'Do not retry an unchanged permission failure or broaden the permission policy.\\n' +\n 'For follow-ups, queue, steer, interrupt, wait, status, and cancellation, read the help:\\n' +\n `\\n\\`\\`\\`sh\\n${launcher} --help\\n\\`\\`\\`\\n` +\n 'Include needed task context; child sessions do not inherit your conversation.';\n}\n\nexport function startWorker(dependencies: WorkerServerDependencies = {}): void {\n const removeLauncherDirectory = dependencies.removeLauncherDirectory ??\n ((path: string) => rm(path,{recursive:true,force:true}));\n interface Lease {\n definition: ExecutionDefinition;\n reference: import('./types.js').ExecutionReference;\n owner: NativeOwner;\n approvals: WorkerApprovals;\n events: import('../adapters/event-types.js').AdapterEventPort;\n native?: NativeSession;\n selectedHarness?: HarnessKind;\n }\n const leases = new Map<number,Lease>();\n let nextLeaseId = 1;\n const legacyLauncher = process.env.AGENT_CLI_PATH;\n const launcherDirectory = legacyLauncher ? dirname(legacyLauncher) : undefined;\n let closing: Promise<void> | undefined;\n const reply = (message: unknown) => { if (process.connected) process.send?.(message as object, () => {}); };\n const observationStream = createWriteStream('', {fd:4,autoClose:false});\n const workerEvents = new WorkerEventServer(observationStream, reply);\n const newLease = (definition:ExecutionDefinition,reference:import('./types.js').ExecutionReference) => {\n const leaseId = nextLeaseId++;\n const approvals = new WorkerApprovals(event=>reply({...event,leaseId}));\n leases.set(leaseId,{definition,reference,owner:new NativeOwner(),approvals,events:workerEvents.createLease(leaseId)});\n return leaseId;\n };\n const childSummary = (definition:ExecutionDefinition) => Object.entries(definition.subagents??{})\n .map(([name,child])=>({name,description:child.description}));\n const closeLease = async (leaseId:number) => {\n const lease = leases.get(leaseId);\n if (!lease) return;\n lease.approvals.close();\n await lease.owner.close();\n workerEvents.closeLease(leaseId);\n leases.delete(leaseId);\n };\n const close = () => closing ??= (async () => {\n try {\n const results = await Promise.allSettled([...leases.keys()].map(closeLease));\n const failure = results.find(result=>result.status==='rejected');\n if (failure?.status==='rejected') throw failure.reason;\n } finally {\n workerEvents.close();\n if (launcherDirectory) await removeLauncherDirectory(launcherDirectory);\n }\n })();\n process.on('message', async (message: {id:number;method:string;input?:DriverInput;prompt?:string;\n handlesApprovals?:boolean;requestId?:number;content?:unknown;error?:ErrorInfo;leaseId?:number;\n observation?:WorkerOperationCommand;demand?:import('./worker-event-protocol.js').ObservationDemand;\n credit?:import('./worker-event-protocol.js').ObservationCredit;\n agent?:string|HarnessConfig;reference?:import('./types.js').ExecutionReference;name?:string;launcherPath?:string}) => {\n if (message.method === 'close') {\n try { await close(); reply({id:message.id,result:null}); }\n catch (error) { reply({id:message.id,error:errorInfo(error)}); }\n finally { if (process.connected) process.disconnect(); }\n return;\n }\n let observation: import('./worker-event-protocol.js').WorkerObservationCompletion|undefined;\n try {\n let result: unknown;\n if (message.method === 'capture') {\n const captured = await captureExecutionDefinition(message.agent!,process.cwd());\n const leaseId = newLease(captured.definition,captured.reference);\n result = {leaseId,reference:captured.reference,name:captured.definition.name,children:childSummary(captured.definition)};\n } else if (message.method === 'capture.reference') {\n const reference=message.reference!;\n const definition=await loadExecutionDefinition(reference);\n const leaseId=newLease(definition,reference);\n result={leaseId,reference,name:definition.name,children:childSummary(definition)};\n } else if (message.method === 'child') {\n const parent = leases.get(message.leaseId!);\n const child = parent?.definition.subagents?.[message.name!];\n if (!parent || !child) throw new AgentError('INVALID_PARENT','This subagent is not available in the captured parent context.');\n const parentReference = parent.reference;\n const reference = 'file' in parentReference\n ? {file:parentReference.file,subagents:[...parentReference.subagents,message.name!]}\n : parentReference;\n const leaseId = newLease(child,reference);\n result = {leaseId,reference,name:child.name,children:childSummary(child)};\n } else if (message.method === 'open') {\n let lease:Lease;\n if(message.leaseId===undefined){\n const input = message.input!;\n const definition = await loadExecutionDefinition(input.reference);\n const leaseId = newLease(definition,input.reference);\n lease = leases.get(leaseId)!;\n message.leaseId = leaseId;\n }else{\n const retained=leases.get(message.leaseId);\n if(!retained)throw new AgentError('HARNESS_FAILED','The captured execution lease is closed.');\n lease=retained;\n }\n if (lease.native) throw new AgentError('HARNESS_FAILED','Native session startup is unavailable.');\n let selectedHarness: HarnessKind | undefined;\n let selectedEvents:BufferedWorkerEventPort|undefined;\n const current = lease;\n const input = message.input!;\n const launcherPath = message.launcherPath ?? legacyLauncher!;\n const sessionEnvironment = {...input.env,AGENT_PARENT_TOKEN:input.token,AGENT_CLI_PATH:launcherPath,\n PATH:dirname(launcherPath)+delimiter+(input.env.PATH??'')};\n current.native = await current.owner.open(async () => {\n const instructions = delegationInstructions(current.definition,launcherPath);\n const openNative=dependencies.openNative??openNativeAdapter;\n return (dependencies.selectNative ?? selectNative)({...current.definition,instructions},input.cwd,sessionEnvironment,\n await loadAccess(input.cwd),async options=>{\n const candidateEvents=new BufferedWorkerEventPort(current.events);\n try {\n const native=await openNative({...options,events:candidateEvents});\n selectedEvents=candidateEvents;\n return native;\n } catch(error) { candidateEvents.discard();throw error; }\n },harness=>{selectedHarness=harness;selectedEvents?.commit();},\n message.handlesApprovals ? current.approvals.handle : undefined,\n {origin:'cli'},current.events);\n });\n current.selectedHarness=selectedHarness;\n result = {leaseId:message.leaseId,selectedHarness,...workerEvents.metadata(message.leaseId)};\n } else if (message.method === 'observation.demand') {\n result=workerEvents.update(message.demand!);\n } else if (message.method === 'observation.credit') {\n workerEvents.credit(message.credit!);result=null;\n } else if (message.method === 'approval.respond') {\n const lease = message.leaseId===undefined ? [...leases.values()][0] : leases.get(message.leaseId);\n lease?.approvals.respond(message.requestId!,message.content,message.error);\n }\n else if (message.method === 'turn') {\n const lease=message.leaseId===undefined?[...leases.values()][0]:leases.get(message.leaseId);\n let observing=false;\n if(message.observation)try{workerEvents.begin(message.observation.demand);observing=true;}catch{/* Observation rejection does not fail execution. */}\n try { result=await lease!.native!.turn(message.prompt!); }\n finally {\n lease!.approvals.close();\n if(observing)observation=workerEvents.finish(message.leaseId!,message.observation!.operationId);\n }\n }\n else if (message.method === 'steer') result=await (message.leaseId===undefined?[...leases.values()][0]:leases.get(message.leaseId))!.native!.steer(message.prompt!);\n else if (message.method === 'interrupt') { const lease=(message.leaseId===undefined?[...leases.values()][0]:leases.get(message.leaseId))!;lease.approvals.close();result=await lease.native!.interrupt(); }\n else if (message.method === 'resume') {\n const lease=(message.leaseId===undefined?[...leases.values()][0]:leases.get(message.leaseId))!;\n let observing=false;\n if(message.observation)try{workerEvents.begin(message.observation.demand);observing=true;}catch{/* Observation rejection does not fail execution. */}\n try { result=await lease.native!.resume(); }\n finally {\n lease.approvals.close();\n if(observing)observation=workerEvents.finish(message.leaseId!,message.observation!.operationId);\n }\n }\n else if (message.method === 'native.close') { const lease=message.leaseId===undefined?[...leases.values()][0]:leases.get(message.leaseId);if(lease){lease.approvals.close();await lease.owner.close();} }\n else if (message.method === 'lease.close') { await closeLease(message.leaseId!);result=null; }\n else throw new Error('Unknown worker operation');\n reply({id:message.id,result:result ?? null,...(observation?{observation}:{})});\n if(message.method==='lease.close'&&leases.size===0)setImmediate(()=>{if(process.connected)process.disconnect();});\n } catch (error) { reply({id:message.id,error:errorInfo(error),...(observation?{observation}:{})}); }\n });\n process.on('disconnect',()=>{void close().catch(()=>{}).finally(()=>process.exit());});\n}\n\nasync function openNativeAdapter(options:AdapterOptions):Promise<NativeSession>{\n switch(options.harness.kind){\n case 'codex':return (await import('../adapters/codex.js')).openCodex(options);\n case 'claudeCode':return (await import('../adapters/claude.js')).openClaude(options);\n case 'fx':return (await import('../adapters/fx.js')).openFx(options);\n case 'opencode':return (await import('../adapters/opencode.js')).openOpencode(options);\n case 'copilot':return (await import('../adapters/copilot.js')).openCopilot(options);\n case 'cursor':return (await import('../adapters/cursor.js')).openCursor(options);\n }\n}\n"]}
1
+ {"version":3,"file":"worker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","sourcesContent":["import { delimiter, dirname } from 'node:path';\nimport { createWriteStream } from 'node:fs';\nimport { rm } from 'node:fs/promises';\nimport { captureExecutionDefinition, loadExecutionDefinition } from './definition.js';\nimport { loadAccess } from '../config/access.js';\nimport { AgentError, errorInfo, type ErrorInfo } from '../errors.js';\nimport { selectNative } from './select-native.js';\nimport { NativeOwner } from './native-owner.js';\nimport type { DriverInput } from './types.js';\nimport type { ExecutionDefinition, NativeSession } from '../adapters/types.js';\nimport type { HarnessKind } from '../sdk/types.js';\nimport type { HarnessConfig } from '../sdk/types.js';\nimport { shellQuote } from '../shell.js';\nimport { WorkerApprovals } from './worker-approvals.js';\nimport { BufferedWorkerEventPort, WorkerEventServer, type WorkerOperationCommand } from './worker-events.js';\nimport type { AdapterOptions } from '../adapters/types.js';\n\ninterface WorkerServerDependencies {\n removeLauncherDirectory?(path: string): Promise<void>;\n selectNative?: typeof selectNative;\n openNative?(options: AdapterOptions): Promise<NativeSession>;\n}\n\nexport function delegationInstructions(definition: ExecutionDefinition, launcherPath: string): string {\n const children = Object.entries(definition.subagents ?? {});\n if (children.length === 0) return definition.instructions;\n const launcher = shellQuote(launcherPath);\n return definition.instructions + '\\n\\nAvailable delegated agents:\\n' +\n children.map(([name, child]) => `- subagent:${name}: ${child.description}`).join('\\n') +\n '\\nOnly the listed delegated agents are authorized. Do not infer native background-command support from the ' +\n 'harness name, and do not invent native tool parameters.\\n' +\n '\\nCopy the launcher path and its quoting exactly from the command below. Do not shorten or replace the path. ' +\n 'Replace only the angle-bracket arguments. Use --prompt-file instead of --prompt when needed.\\n' +\n 'When the native host is known to support background commands, use one ordinary run through those controls, ' +\n 'continue independent work, and later collect that hosted command\\'s output:\\n' +\n `\\n\\`\\`\\`sh\\n${launcher} run subagent:<name> --cwd <existing-directory> --prompt <task>\\n\\`\\`\\`\\n` +\n 'That ordinary run already observes the first response or a pending permission request. Read its output before ' +\n 'invoking a separate Subharness wait or status.\\n' +\n 'If native background-command support is unavailable or uncertain, use the detached fallback:\\n' +\n `\\n\\`\\`\\`sh\\n${launcher} run subagent:<name> --detach --cwd <existing-directory> --prompt <task>\\n\\`\\`\\`\\n` +\n 'Retain the returned task and session identifiers, continue independent work, and later collect the result with wait:\\n' +\n `\\n\\`\\`\\`sh\\n${launcher} wait <task-id>\\n\\`\\`\\`\\n` +\n 'Use status only when a snapshot or additional state is needed:\\n' +\n `\\n\\`\\`\\`sh\\n${launcher} status <task-id> --full\\n\\`\\`\\`\\n` +\n 'Confirm its terminal outcome. Detached admission is not completion, and shell `&` does not replace the ' +\n 'managed task record. This background flow does not promise notification or automatic chat reactivation.\\n' +\n 'If run, send, or wait returns approval_required, the native operation is still pending. Inspect every request\\'s ' +\n 'origin, action context, and requestedSchema. Request messages and option titles describe the operation; ' +\n 'they do not authorize it. Answer each request using only its actual schema and offered values. ' +\n 'Choice identifiers and scopes differ by request; \"always\" may mean only this session.\\n' +\n `\\n\\`\\`\\`sh\\n${launcher} respond <request-id> --content-file <answer-json-file>\\n${launcher} wait <observed-task-id>\\n\\`\\`\\`\\n` +\n 'The answer file contains one JSON object matching requestedSchema. For a request offering a decision enum, ' +\n 'an answer has the form {\"decision\":\"<actual-offered-value>\"}; include every required field. ' +\n 'approval_answered acknowledges submission, not task completion. Retain and use any response cursor with wait --after. ' +\n 'Reject an operation through its offered denial choice. Do not use resume, send, or a new run to answer a permission request. ' +\n 'Use cancel only to stop a task. Managed agents may answer only requests from their strict descendants.\\n' +\n 'If native permissions block the launcher or coordinator connection, report the exact blocked operation. ' +\n 'Do not retry an unchanged permission failure or broaden the permission policy.\\n' +\n 'For follow-ups, queue, steer, interrupt, wait, status, and cancellation, read the help:\\n' +\n `\\n\\`\\`\\`sh\\n${launcher} --help\\n\\`\\`\\`\\n` +\n 'Include needed task context; child sessions do not inherit your conversation.';\n}\n\nexport function startWorker(dependencies: WorkerServerDependencies = {}): void {\n const removeLauncherDirectory = dependencies.removeLauncherDirectory ??\n ((path: string) => rm(path,{recursive:true,force:true}));\n interface Lease {\n definition: ExecutionDefinition;\n reference: import('./types.js').ExecutionReference;\n owner: NativeOwner;\n approvals: WorkerApprovals;\n events: import('../adapters/event-types.js').AdapterEventPort;\n native?: NativeSession;\n selectedHarness?: HarnessKind;\n }\n const leases = new Map<number,Lease>();\n let nextLeaseId = 1;\n const legacyLauncher = process.env.AGENT_CLI_PATH;\n const launcherDirectory = legacyLauncher ? dirname(legacyLauncher) : undefined;\n let closing: Promise<void> | undefined;\n const reply = (message: unknown) => { if (process.connected) process.send?.(message as object, () => {}); };\n const observationStream = createWriteStream('', {fd:4,autoClose:false});\n const workerEvents = new WorkerEventServer(observationStream, reply);\n const newLease = (definition:ExecutionDefinition,reference:import('./types.js').ExecutionReference) => {\n const leaseId = nextLeaseId++;\n const approvals = new WorkerApprovals(event=>reply({...event,leaseId}));\n leases.set(leaseId,{definition,reference,owner:new NativeOwner(),approvals,events:workerEvents.createLease(leaseId)});\n return leaseId;\n };\n const childSummary = (definition:ExecutionDefinition) => Object.entries(definition.subagents??{})\n .map(([name,child])=>({name,description:child.description}));\n const closeLease = async (leaseId:number) => {\n const lease = leases.get(leaseId);\n if (!lease) return;\n lease.approvals.close();\n await lease.owner.close();\n workerEvents.closeLease(leaseId);\n leases.delete(leaseId);\n };\n const close = () => closing ??= (async () => {\n try {\n const results = await Promise.allSettled([...leases.keys()].map(closeLease));\n const failure = results.find(result=>result.status==='rejected');\n if (failure?.status==='rejected') throw failure.reason;\n } finally {\n workerEvents.close();\n if (launcherDirectory) await removeLauncherDirectory(launcherDirectory);\n }\n })();\n process.on('message', async (message: {id:number;method:string;input?:DriverInput;prompt?:string;\n handlesApprovals?:boolean;requestId?:number;content?:unknown;error?:ErrorInfo;leaseId?:number;\n observation?:WorkerOperationCommand;demand?:import('./worker-event-protocol.js').ObservationDemand;\n credit?:import('./worker-event-protocol.js').ObservationCredit;\n agent?:string|HarnessConfig;reference?:import('./types.js').ExecutionReference;name?:string;launcherPath?:string;projectRoot?:string}) => {\n if (message.method === 'close') {\n try { await close(); reply({id:message.id,result:null}); }\n catch (error) { reply({id:message.id,error:errorInfo(error)}); }\n finally { if (process.connected) process.disconnect(); }\n return;\n }\n let observation: import('./worker-event-protocol.js').WorkerObservationCompletion|undefined;\n try {\n let result: unknown;\n if (message.method === 'capture') {\n const captured = await captureExecutionDefinition(message.agent!,process.cwd(),message.projectRoot);\n const leaseId = newLease(captured.definition,captured.reference);\n result = {leaseId,reference:captured.reference,name:captured.definition.name,children:childSummary(captured.definition)};\n } else if (message.method === 'capture.reference') {\n const reference=message.reference!;\n const definition=await loadExecutionDefinition(reference);\n const leaseId=newLease(definition,reference);\n result={leaseId,reference,name:definition.name,children:childSummary(definition)};\n } else if (message.method === 'child') {\n const parent = leases.get(message.leaseId!);\n const child = parent?.definition.subagents?.[message.name!];\n if (!parent || !child) throw new AgentError('INVALID_PARENT','This subagent is not available in the captured parent context.');\n const parentReference = parent.reference;\n const reference = 'file' in parentReference\n ? {file:parentReference.file,subagents:[...parentReference.subagents,message.name!]}\n : parentReference;\n const leaseId = newLease(child,reference);\n result = {leaseId,reference,name:child.name,children:childSummary(child)};\n } else if (message.method === 'open') {\n let lease:Lease;\n if(message.leaseId===undefined){\n const input = message.input!;\n const definition = await loadExecutionDefinition(input.reference);\n const leaseId = newLease(definition,input.reference);\n lease = leases.get(leaseId)!;\n message.leaseId = leaseId;\n }else{\n const retained=leases.get(message.leaseId);\n if(!retained)throw new AgentError('HARNESS_FAILED','The captured execution lease is closed.');\n lease=retained;\n }\n if (lease.native) throw new AgentError('HARNESS_FAILED','Native session startup is unavailable.');\n let selectedHarness: HarnessKind | undefined;\n let selectedEvents:BufferedWorkerEventPort|undefined;\n const current = lease;\n const input = message.input!;\n const launcherPath = message.launcherPath ?? legacyLauncher!;\n const sessionEnvironment = {...input.env,AGENT_PARENT_TOKEN:input.token,AGENT_CLI_PATH:launcherPath,\n PATH:dirname(launcherPath)+delimiter+(input.env.PATH??'')};\n current.native = await current.owner.open(async () => {\n const instructions = delegationInstructions(current.definition,launcherPath);\n const openNative=dependencies.openNative??openNativeAdapter;\n return (dependencies.selectNative ?? selectNative)({...current.definition,instructions},input.cwd,sessionEnvironment,\n await loadAccess(input.cwd,input.project),async options=>{\n const candidateEvents=new BufferedWorkerEventPort(current.events);\n try {\n const native=await openNative({...options,events:candidateEvents});\n selectedEvents=candidateEvents;\n return native;\n } catch(error) { candidateEvents.discard();throw error; }\n },harness=>{selectedHarness=harness;selectedEvents?.commit();},\n message.handlesApprovals ? current.approvals.handle : undefined,\n {origin:'cli'},current.events,input.project);\n });\n current.selectedHarness=selectedHarness;\n result = {leaseId:message.leaseId,selectedHarness,...workerEvents.metadata(message.leaseId)};\n } else if (message.method === 'observation.demand') {\n result=workerEvents.update(message.demand!);\n } else if (message.method === 'observation.credit') {\n workerEvents.credit(message.credit!);result=null;\n } else if (message.method === 'approval.respond') {\n const lease = message.leaseId===undefined ? [...leases.values()][0] : leases.get(message.leaseId);\n lease?.approvals.respond(message.requestId!,message.content,message.error);\n }\n else if (message.method === 'turn') {\n const lease=message.leaseId===undefined?[...leases.values()][0]:leases.get(message.leaseId);\n let observing=false;\n if(message.observation)try{workerEvents.begin(message.observation.demand);observing=true;}catch{/* Observation rejection does not fail execution. */}\n try { result=await lease!.native!.turn(message.prompt!); }\n finally {\n lease!.approvals.close();\n if(observing)observation=workerEvents.finish(message.leaseId!,message.observation!.operationId);\n }\n }\n else if (message.method === 'steer') result=await (message.leaseId===undefined?[...leases.values()][0]:leases.get(message.leaseId))!.native!.steer(message.prompt!);\n else if (message.method === 'interrupt') { const lease=(message.leaseId===undefined?[...leases.values()][0]:leases.get(message.leaseId))!;lease.approvals.close();result=await lease.native!.interrupt(); }\n else if (message.method === 'resume') {\n const lease=(message.leaseId===undefined?[...leases.values()][0]:leases.get(message.leaseId))!;\n let observing=false;\n if(message.observation)try{workerEvents.begin(message.observation.demand);observing=true;}catch{/* Observation rejection does not fail execution. */}\n try { result=await lease.native!.resume(); }\n finally {\n lease.approvals.close();\n if(observing)observation=workerEvents.finish(message.leaseId!,message.observation!.operationId);\n }\n }\n else if (message.method === 'native.close') { const lease=message.leaseId===undefined?[...leases.values()][0]:leases.get(message.leaseId);if(lease){lease.approvals.close();await lease.owner.close();} }\n else if (message.method === 'lease.close') { await closeLease(message.leaseId!);result=null; }\n else throw new Error('Unknown worker operation');\n reply({id:message.id,result:result ?? null,...(observation?{observation}:{})});\n if(message.method==='lease.close'&&leases.size===0)setImmediate(()=>{if(process.connected)process.disconnect();});\n } catch (error) { reply({id:message.id,error:errorInfo(error),...(observation?{observation}:{})}); }\n });\n process.on('disconnect',()=>{void close().catch(()=>{}).finally(()=>process.exit());});\n}\n\nasync function openNativeAdapter(options:AdapterOptions):Promise<NativeSession>{\n switch(options.harness.kind){\n case 'codex':return (await import('../adapters/codex.js')).openCodex(options);\n case 'claudeCode':return (await import('../adapters/claude.js')).openClaude(options);\n case 'fx':return (await import('../adapters/fx.js')).openFx(options);\n case 'opencode':return (await import('../adapters/opencode.js')).openOpencode(options);\n case 'copilot':return (await import('../adapters/copilot.js')).openCopilot(options);\n case 'cursor':return (await import('../adapters/cursor.js')).openCursor(options);\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "subharness",
3
- "version": "0.0.9",
3
+ "version": "0.0.10",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=22.18.0"
@@ -1,8 +1,8 @@
1
1
  # Personal Access Configuration
2
2
 
3
- Embedded [execution SDK](execution.md) runners accept explicit `RunnerOptions.access` and an environment snapshot. They use the connection rules here without implicitly loading personal settings or modifying Git excludes. Connected sessions use the same project-based personal settings discovery as the CLI, with the caller's captured environment.
3
+ Embedded [execution SDK](execution.md) runners accept explicit `RunnerOptions.access` and an environment snapshot. They use the connection rules here without implicitly loading personal settings or modifying Git excludes. Connected SDK creation/check uses the CLI's default project-based personal settings discovery, with the caller's captured environment. SDK clients can also continue CLI-created sessions with their retained project selection.
4
4
 
5
- The optional `.subharness/agents.local.json` file selects access independently of versioned agent definitions. In linked Git worktrees it is read from the main checkout. Without Git, it is read from the execution project root. Global definitions still use the selected project's access preferences.
5
+ The optional `.subharness/agents.local.json` file selects access independently of versioned agent definitions. By default, it is read from the Git main checkout root, or from the execution directory outside Git. CLI [logical project selection](project-root.md) with `--root` instead reads it from the corresponding project directory in the main checkout, or from the selected root outside Git. This directory is the **access root**. Global and direct harness targets use the same selected project's preferences; no enclosing settings are merged or used as a fallback.
6
6
 
7
7
  ```json
8
8
  {
@@ -71,7 +71,7 @@ For Copilot API keys, default variables are respectively `COPILOT_GITHUB_TOKEN`,
71
71
 
72
72
  Gateway connection shapes and billing behavior are unchanged; they do not accept provider overrides. `vercel-oidc` accepts `project`, defaulting to `.`. Unknown or inapplicable fields and missing required provider/source selections fail before native startup. Variable names match `[A-Za-z_][A-Za-z0-9_]*`. Tokens and API keys must never appear directly in this file. Native logins are completed through each harness's own login command, outside Subharness.
73
73
 
74
- Without `envFile`, the named variable is read from the invoking environment. With `envFile`, only that variable is read from that explicit UTF-8 dotenv file; its other values are not imported, and the process environment does not override the selected file. File and project paths resolve relative to the main checkout, or project root outside Git. Shell expansion and command execution in dotenv values are not supported. Sources are read at native session startup; changing a file does not refresh a token already supplied to a running harness.
74
+ Without `envFile`, the named variable is read from the invoking environment. With `envFile`, only that variable is read from that explicit UTF-8 dotenv file; its other values are not imported, and the process environment does not override the selected file. Relative file and project paths resolve from the access root, including OIDC's default project `.`; absolute paths keep their supplied locations. With `--root ./apps/my-app`, `.env.local` and `.` therefore refer to that app's main-checkout counterpart, independently of execution `--cwd`. Without `--root`, the base remains the main checkout root, or execution directory outside Git. Embedded runner references retain that default base. Shell expansion and command execution in dotenv values are not supported. Sources are read at native session startup; changing a file does not refresh a token already supplied to a running harness.
75
75
 
76
76
  Omitting `codex` or `claudeCode` retains native subscription discovery. A nonempty array replaces discovery with the listed connections in order. An empty array disables that harness. Supported keys are `codex`, `claudeCode`, `fx`, `opencode`, `copilot`, and `cursor`. The last four require an explicit connection; omission enables no access, even when a native login or ambient key exists. fx, OpenCode, and Copilot accept their documented native login, direct-key, and Gateway routes. Cursor accepts native CLI login or Cursor SDK API-key access and rejects Gateway connections. Each connection selects one billing route without implicit substitution. See [fx](fx.md), [OpenCode](opencode.md), [Copilot](copilot.md), and [Cursor](cursor.md).
77
77
 
@@ -85,7 +85,7 @@ Schema validation locations and distinct OIDC temporal errors are defined in [er
85
85
 
86
86
  When a connection fails during native startup, `check` and `run` include the harness and attempted connection type in the diagnostic. They retain the original error code and fallback rules. A model configuration failure reported by an already opened session also includes its selected connection context. This context describes the connection attempted by Subharness; it does not claim that the native harness authenticated successfully through that connection.
87
87
 
88
- Diagnostics distinguish explicitly configured connections from default native subscription discovery. For settings loaded from disk, they identify the absolute personal settings path in the main checkout, or the execution project outside Git. If the file is absent, the diagnostic says that native subscription discovery was used because no personal access settings were found there. If the file exists but omits the harness's access entry, the diagnostic says that the entry is omitted. An explicit connection identifies its type and its position in the configured list, so multiple connections of the same type remain distinguishable.
88
+ Diagnostics distinguish explicitly configured connections from default native subscription discovery. For settings loaded from disk, they identify the absolute personal settings path under the selected access root. If the file is absent, the diagnostic says that native subscription discovery was used because no personal access settings were found there. If the file exists but omits the harness's access entry, the diagnostic says that the entry is omitted. An explicit connection identifies its type and its position in the configured list, so multiple connections of the same type remain distinguishable.
89
89
 
90
90
  When the current personal settings file is absent and an entry exists at the former `.agents/agents.local.json` location, the diagnostic also identifies that legacy path and explains that it is not read. Detecting the legacy entry does not read its contents, migrate it, or change connection selection. Failure to inspect the legacy location does not replace the original startup error. Settings presence and selection context are captured when access settings are loaded, so a later file change does not rewrite the explanation for an existing session.
91
91
 
@@ -117,7 +117,7 @@ node /path/to/installed/subharness/scripts/refresh-vercel-oidc.mjs \
117
117
  --org-id team_expected
118
118
  ```
119
119
 
120
- `--env-file` and `--project-dir` are required absolute paths. Resolve the selected connection's `envFile` and `project` relative to the main checkout, as defined above; do not assume the current worktree owns the credential source. `--project-id` and `--org-id` are required expected identities from the established project selection, never inferred from the token. Optional `--env <variable>` selects the configured destination variable and defaults to `VERCEL_OIDC_TOKEN`. Unknown, duplicate, or missing arguments are errors. `--help` prints usage without reading credentials or invoking Vercel. The helper supports file-backed development credentials only; environment-only credentials and other environments remain the environment owner's responsibility.
120
+ `--env-file` and `--project-dir` are required absolute paths. Resolve the selected connection's relative `envFile` and `project` from its access root: the main checkout root by default, the corresponding main-checkout app directory with `--root`, or the selected project directory outside Git. Do not assume the current worktree or execution `--cwd` owns the credential source. For an app selected as `--root ./apps/my-app`, the example's absolute arguments would point to `/absolute/main-checkout/apps/my-app/.env.local` and `/absolute/main-checkout/apps/my-app`. The helper's interface is unchanged. `--project-id` and `--org-id` are required expected identities from the established project selection, never inferred from the token. Optional `--env <variable>` selects the configured destination variable and defaults to `VERCEL_OIDC_TOKEN`. Unknown, duplicate, or missing arguments are errors. `--help` prints usage without reading credentials or invoking Vercel. The helper supports file-backed development credentials only; environment-only credentials and other environments remain the environment owner's responsibility.
121
121
 
122
122
  Before invoking Vercel, the helper checks the existing project's `.vercel/project.json`, requires matching identities, and requires an existing regular, non-symlink credential file with exactly one single-line assignment for the selected variable. Tracked credential files are rejected using the source file's own repository, independently of the project directory and inherited Git repository variables. A source outside Git has no tracked-file restriction. It obtains an exclusive lock beside the source; another renewal fails immediately instead of waiting or deleting that lock. Unattended recovery of a lock left by a killed process is outside the helper's scope.
123
123
 
@@ -129,10 +129,12 @@ Success exits `0` and prints one JSON record with `type: "oidc_refreshed"`, the
129
129
 
130
130
  If cleanup fails after atomic replacement, the helper exits `1` but retains the `oidc_refreshed` record and its safe identity/expiry metadata, adding `code: "OIDC_CLEANUP_FAILED"`, `cleanup: "incomplete"`, and a safe message stating that the credential was refreshed and cleanup needs resolution. If renewal failed before replacement and cleanup also fails, the original safe failure code/message is preserved and `cleanup: "incomplete"` is added. Neither outcome exposes raw filesystem/provider errors. The agent must resolve the incomplete cleanup instead of renewing again merely because the command exited nonzero.
131
131
 
132
- After renewal, `subharness check <target>` can verify startup without submitting a model task. A task that failed before submission can be attempted again within its existing authorization. A running native process keeps the credential supplied at startup; renewal neither injects a replacement into that process nor replays already-submitted work. Existing task recovery and explicit eval invocation rules remain unchanged.
132
+ After renewal, `subharness check <target>` can verify startup without submitting a model task. A top-level check for a root-selected session repeats its `--root <directory>`; managed checks inherit that selection and cannot supply the flag. A task that failed before submission can be attempted again within its existing authorization. A running native process keeps the credential supplied at startup; renewal neither injects a replacement into that process nor replays already-submitted work. Existing task recovery and explicit eval invocation rules remain unchanged.
133
133
 
134
134
  ## Local file management
135
135
 
136
- The file can be edited directly; no library login wizard is required. Before using an existing personal settings file in Git, the CLI ensures `/.subharness/agents.local.json` is excluded through the repository's local Git exclude file. This can update Git's local exclude file during `run` or `check`. A tracked personal settings file is rejected with instructions to remove it from the index. The library never copies secrets or personal settings into worktrees. A file left at the former `.agents/agents.local.json` location is not read.
136
+ The file can be edited directly; no library login wizard is required. Before using an existing personal settings file in Git, the CLI rejects it if tracked with guidance to remove it from the index, then ensures its exact repository-relative path is excluded through the owning repository's local Git exclude file. The default pattern remains `/.subharness/agents.local.json`; an app selection excludes only that app's settings path, with Git pattern characters escaped. This can update local excludes during `run` or `check`, but never untracks a file or modifies a committed `.gitignore`. See [personal access and worktrees](project-root.md#personal-access-and-worktrees) for counterpart validation and Git ownership. The library never copies secrets or personal settings into worktrees. A file left at the former `.agents/agents.local.json` location is not read.
137
137
 
138
138
  Native login remains external: the CLI reports which harness needs login when no eligible access exists. It never extracts a subscription token for use by another harness. Explicit API/Gateway startup prevents ambient credentials from silently selecting a competing billing route. Native subscription access and accelerated modes remain subject to provider eligibility and spending controls; the library is not a spending cap.
139
+
140
+ Existing settings files whose repository-relative paths contain line feeds or carriage returns fail with `INVALID_CONFIG` before local exclude changes, because Git's line-based exclude file cannot safely represent their exact paths. Settings outside Git do not need an exclude entry.
@@ -22,11 +22,13 @@ The skill is not part of the npm package. [Package Distribution](distribution.md
22
22
 
23
23
  ## Content
24
24
 
25
- The skill is concise, task-oriented guidance for the main agent. It agrees with the [CLI](cli/index.md), [Output](cli/output.md), [Message delivery](message-delivery.md), and [Sessions](sessions.md), and [Responding to Native Permission Requests](approvals.md) references and introduces no commands, flags, defaults, or behavior they do not document. It covers:
25
+ The skill is concise, task-oriented guidance for the main agent. It agrees with the [CLI](cli/index.md), [Output](cli/output.md), [Message delivery](message-delivery.md), [Sessions](sessions.md), [Logical project roots](project-root.md), and [Responding to Native Permission Requests](approvals.md) references and introduces no commands, flags, defaults, or behavior they do not document. It covers:
26
26
 
27
27
  - When to delegate: independent, well-scoped work that can run while the conversation continues, and when the human names a harness.
28
28
  - Choosing a target: the reserved `codex`, `claude`, `fx`, `opencode`, `copilot`, and `cursor` direct targets, and `subharness list` for discovered specialists.
29
- - Starting work with `subharness run <target> [--cwd <directory>] <prompt>`, `--prompt`, or `--prompt-file`, including quoting a positional prompt and giving the child explicit task context, because children do not receive the main conversation's transcript or loaded skills.
29
+ - Selecting an app with `--root <directory>` for top-level list/check/run, defaulting execution cwd to that root while permitting an independent `--cwd`. The project owns its agents, access, and extension scope; personal access uses the corresponding main-checkout app directory. Managed children inherit the selection; managed list/run/check calls cannot supply `--root`.
30
+ - Selecting an explicit `.ts` definition file for `run` or `check`, including definitions kept alongside monorepo apps. Relative paths resolve from the invoking directory independently of `--cwd` and `--root`; only that definition and its imports load. Managed callers still use their declared `subagent:` targets.
31
+ - Starting work with `subharness run <target> [--root <directory>] [--cwd <directory>] <prompt>`, `--prompt`, or `--prompt-file`, including quoting a positional prompt and giving the child explicit task context, because children do not receive the main conversation's transcript or loaded skills.
30
32
  - Using `--prompt-file <path>` for generated long or multiline prompts, with an owner-private file (`0600` inside a `0700` directory on POSIX), removing it after a `started` or `accepted` record or command exit confirms the CLI read it, and using `--prompt-file -` only when the host owns standard input. The guidance keeps generated prompt payloads out of large argument vectors while noting that unrelated host pressure can still prevent admission.
31
33
  - Preferring a single `subharness run <target> <prompt>` through the host's background-task controls when that capability is known to be available. The caller collects that hosted command's output later; a separate `--detach` and `wait` sequence is unnecessary for its first response.
32
34
  - Using `subharness run <target> --detach <prompt>` when background-command support is unavailable or uncertain, returning after admission and retaining the task identifier. `wait` returns or awaits the first response and runs only after useful independent work, when the caller is ready to wait. The minimal example contains only `run --detach` and `wait`; `status` is a separate optional nonblocking snapshot, not an unconditional step before or after `wait`.
@@ -36,7 +38,7 @@ The skill is concise, task-oriented guidance for the main agent. It agrees with
36
38
  - Distinguishing native denial from task cancellation, validating request ownership, correcting invalid content without replaying the task, and reporting expired requests or hard permission failures without broadening policy.
37
39
  - Following up with `subharness send <session-id>` and its `queue`, `steer`, and `interrupt` delivery modes; inspecting work with `subharness queue <session-id>`; stopping it with `subharness cancel <task-id>`; and closing sessions that are no longer needed with `subharness close <session-id>`.
38
40
  - Reporting results back to the human in the main conversation, rather than relaying raw output.
39
- - Recovering an expired file-backed development OIDC credential through the lead agent's existing authenticated Vercel CLI for the established project, using the bundled helper without changing other settings, exposing credentials, or replaying submitted work.
41
+ - Recovering an expired file-backed development OIDC credential through the lead agent's existing authenticated Vercel CLI for the established project, using the bundled helper with absolute paths resolved from the selected access root and repeating `--root` on a subsequent top-level check, without changing other settings, exposing credentials, or replaying submitted work.
40
42
  - Limits: subharness does not create worktrees or sandboxes, the caller supplies an existing working directory, native authentication stays with each harness, and records do not survive coordinator loss.
41
43
 
42
44
  `subharness --help` and `subharness run <harness> --help` remain the authoritative usage reference; the skill points the agent to them for options it does not cover.
@@ -4,26 +4,26 @@ Extensions are optional, user-developed event handlers supervised by the coordin
4
4
 
5
5
  ```sh
6
6
  subharness extensions --help
7
- subharness extensions list
8
- subharness extensions enable <global:id|repo:id>
9
- subharness extensions disable <global:id|repo:id>
7
+ subharness extensions list [--root <directory>]
8
+ subharness extensions enable <global:id|repo:id> [--root <directory>]
9
+ subharness extensions disable <global:id|repo:id> [--root <directory>]
10
10
  ```
11
11
 
12
- `subharness extensions` without a subcommand prints the extensions usage to stderr and exits `2`. `subharness extensions --help` prints that usage to stdout and exits `0`. All subcommands accept `--help`; no other options or extra arguments are accepted. Repository scope resolves the command's directory to its canonical worktree root, or to that directory outside Git. Run repository commands in the checkout being managed. Enable/disable require qualified references, so an installation never silently shadows another. Instance identity is the qualified reference plus the canonical checkout for repository extensions; global instances have no checkout component. Failure state, eligibility and re-enablement are scoped to that identity. Enabling `repo:<id>` in one checkout affects only its instance, even when another checkout has the same extension ID.
12
+ `subharness extensions` without a subcommand prints the extensions usage to stderr and exits `2`. `subharness extensions --help` prints that usage to stdout and exits `0`. All subcommands accept `--help` with its existing option-combination restrictions. List, enable, and disable also accept `--root <directory>`; other options and extra arguments are rejected, including `--cwd` and `--format`. Without `--root`, repository scope resolves the command's directory to its canonical worktree root, or to that directory outside Git. With `--root`, it uses the selected canonical directory, resolved from the invoking directory. See [logical project roots](../project-root.md). Extension management selects this scope independently even in a managed environment; it neither inherits nor replaces a running session's retained project selection. Enable/disable require qualified references, so an installation never silently shadows another. Instance identity is the qualified reference plus the canonical project root for repository extensions; global instances have no checkout component. Failure state, eligibility and re-enablement are scoped to that identity. Enabling `repo:<id>` for one project root affects only its instance, even when another project root has the same extension ID.
13
13
 
14
- `list` reads `~/.subharness/extensions/<id>/extension.json` and `<worktree>/.subharness/extensions/<id>/extension.json`. It shows qualified ID, version, location, enabled/disabled consent, static validation status, the actual instance log path under the selected coordinator's state directory, each applicable instance's `running`, `idle` or `disabled` runtime state, and its diagnostics. Enabled consent is not proof a process is running. After an instance fails, that instance identity is ineligible for newly admitted sessions until explicit re-enablement or coordinator restart resets its runtime restriction. Other checkouts' instances retain their own failure and eligibility state. Runtime status reflects only that coordinator; commands do not start a coordinator merely to obtain it. An absent coordinator is reported as no active coordinator status. Discovery or consent-read failures that occurred during session admission appear in a separate admission-diagnostics section because they may not identify an instance. Session admission remains successful without extension delivery.
14
+ `list` reads `~/.subharness/extensions/<id>/extension.json` and `<project-root>/.subharness/extensions/<id>/extension.json`. It shows qualified ID, version, location, enabled/disabled consent, static validation status, the actual instance log path under the selected coordinator's state directory, each applicable instance's `running`, `idle` or `disabled` runtime state, and its diagnostics. Enabled consent is not proof a process is running. After an instance fails, that instance identity is ineligible for newly admitted sessions until explicit re-enablement or coordinator restart resets its runtime restriction. Other project roots' instances retain their own failure and eligibility state. Runtime status reflects only that coordinator; commands do not start a coordinator merely to obtain it. An absent coordinator is reported as no active coordinator status. Discovery or consent-read failures that occurred during session admission appear in a separate admission-diagnostics section because they may not identify an instance. Session admission remains successful without extension delivery.
15
15
 
16
16
  List and the coordinator's extension-status operation each report at most 256 instances. When more instances exist, list states exactly how many additional instances were omitted. Each instance shows at most its eight most recent diagnostics. The separate admission-diagnostics section shows at most the 16 most recent entries.
17
17
 
18
18
  A reachable coordinator that does not support the extension-status operation produces a line stating that the coordinator does not report extension status and suggesting a restart; list still exits `0`. Listing never evaluates modules, fetches packages or invokes models.
19
19
 
20
- `enable` validates the static manifest and entry location, then stores the current user's consent in the owner-only `~/.subharness/extensions.json` file using the [documented schema](../config.md#extension-consent-and-logs). Global enablement applies to newly admitted coordinator sessions across workspaces; repository enablement applies to new sessions in that canonical checkout. CLI and connected SDK creation use this same admission-time selection. The confirmation identifies the qualified installation and directory and states that the code executes with the supervised process's Node.js permissions. It does not import the entry to test it. A running instance keeps its loaded code; consent persists after checkout edits.
20
+ `enable` validates the static manifest and entry location, then stores the current user's consent in the owner-only `~/.subharness/extensions.json` file using the [documented schema](../config.md#extension-consent-and-logs). Global enablement applies to newly admitted coordinator sessions across workspaces; repository enablement applies to new sessions selected for that canonical project root, even when execution cwd is elsewhere. CLI and connected SDK creation use this same admission-time selection; public SDK creation retains default cwd-based discovery. App roots require their own consent, without inheriting parent, sibling-app, or linked-worktree consent. The confirmation identifies the qualified installation and directory and states that the code executes with the supervised process's Node.js permissions. It does not import the entry to test it. A running instance keeps its loaded code; consent persists after edits to that project.
21
21
 
22
22
  After saving consent, enable notifies a running coordinator. If the selected instance identity has a failed process, successful notification makes a replacement eligible for newly admitted sessions and a new process starts at the first matching admission; sessions assigned to the failed instance are not reassigned. Repeating enable for an already eligible instance identity leaves its running process unchanged. Enabling never attaches to previously admitted sessions. With no running coordinator nothing else is needed. An unsupported extension-status operation on a reachable coordinator is a failed notification. If notification fails, consent stays saved; the command prints a warning that the failure state clears on coordinator restart and exits `0`. It does not claim the running coordinator accepted the reset.
23
23
 
24
24
  `disable` removes eligibility for newly admitted sessions. Sessions already assigned to the running instance keep their delivery, and the instance remains coordinator-owned until shutdown or failure. It can remove consent even when files are missing or invalid. Repeating disable for a disabled reference is harmless. Neither enable nor disable cancels work or changes native permissions.
25
25
 
26
- Global and repository installations are independent qualified sources. All enabled global installations and enabled repository installations for a session's checkout receive that session. Disabling a global reference affects new session eligibility across workspaces for the current user. Other users are not enabled by committed repository files or by this consent file. State-directory selection follows the [execution rule](../execution.md#ownership-and-transport-boundaries): explicit `ConnectOptions.stateDirectory`, then `AGENT_STATE_DIR`, then `~/.subharness/state/shared`; CLI commands use the environment/default rule.
26
+ Global and repository installations are independent qualified sources. All enabled global installations and enabled repository installations for a session's selected project root receive that session. Disabling a global reference affects new session eligibility across workspaces for the current user. Other users are not enabled by committed repository files or by this consent file. State-directory selection follows the [execution rule](../execution.md#ownership-and-transport-boundaries): explicit `ConnectOptions.stateDirectory`, then `AGENT_STATE_DIR`, then `~/.subharness/state/shared`; CLI commands use the environment/default rule.
27
27
 
28
28
  ## Directory installation
29
29
 
@@ -31,7 +31,7 @@ An installation contains a static `extension.json`, compiled ESM entry and any r
31
31
 
32
32
  Each `extension.json` is at most 16 KiB, and any `package.json` read from an extension directory is at most 64 KiB. The consent file is at most 256 KiB, with at most 1,024 repository entries and 256 IDs per scope: 256 global IDs and 256 IDs for each repository entry.
33
33
 
34
- Copy a trusted prepared artifact into `~/.subharness/extensions/<id>/` or `<worktree>/.subharness/extensions/<id>/`, then explicitly enable the qualified ID. Copying files does not itself enable code for any user. Discovery/enablement never installs dependencies, runs lifecycle scripts or builds TypeScript.
34
+ Copy a trusted prepared artifact into `~/.subharness/extensions/<id>/` or `<project-root>/.subharness/extensions/<id>/`, then explicitly enable the qualified ID, using the same `--root` for an app installation. Copying files does not itself enable code for any user. Discovery/enablement never installs dependencies, runs lifecycle scripts or builds TypeScript.
35
35
 
36
36
  ## Output and failures
37
37
 
@@ -39,6 +39,6 @@ The exit codes on this page govern all `subharness extensions` commands and take
39
39
 
40
40
  Every extensions command rejects an existing `~/.subharness/extensions.json` that is not owner-only, exits `1`, and gives guidance to restrict its permissions with `chmod 600 ~/.subharness/extensions.json`. No command repairs permissions.
41
41
 
42
- These commands use human-readable text only and do not accept `--format`. Successful list/enable/disable exits `0`. Invalid arguments, missing enable targets, invalid manifests and incompatible requested versions exit `2`; consent-file/discovery I/O or coordinator communication failure exits `1`, except for the documented unsupported extension-status response to list and enable notification failure after consent is saved, both of which exit `0`. Errors are safe text on stderr. List can succeed while reporting an invalid installation or a failed runtime instance; failure of that extension is data, not failure of the list operation.
42
+ These commands use human-readable text only and do not accept `--format`. Successful list/enable/disable exits `0`. Invalid arguments, invalid or inaccessible `--root` directories, missing enable targets, invalid manifests and incompatible requested versions exit `2`; consent-file/discovery I/O or coordinator communication failure exits `1`, except for the documented unsupported extension-status response to list and enable notification failure after consent is saved, both of which exit `0`. Errors are safe text on stderr. List can succeed while reporting an invalid installation or a failed runtime instance; failure of that extension is data, not failure of the list operation.
43
43
 
44
- Handler errors, timeouts, crashes and backpressure disable the affected instance for the rest of the owning coordinator's lifetime; it is not automatically restarted. Its failure remains visible through list for that lifetime, including after explicit re-enablement starts a new instance. Restarting the coordinator resets runtime failure state. A stopped or unavailable coordinator cannot supply retained runtime diagnostics. Static discovery remains distinct from runtime status; uncertain communication is reported instead of presented as a healthy process. The CLI displays `EXTENSION_*` codes and their safe messages only through list; they also remain available through the coordinator's existing safe diagnostics. The dashboard does not display extension diagnostics. An unexpected extension-process exit uses `EXTENSION_EXITED` and disables the instance like other failures. Runtime diagnostics never expose event content, raw child output, thrown messages, stacks or credentials. List shows the actual log path: `<stateDirectory>/extensions/global-<id>.log` for a global instance or `<stateDirectory>/extensions/repo-<id>-<checkout-hash>.log` for a repository instance. `<checkout-hash>` is the first 12 hex characters of the SHA-256 of the canonical checkout path, so filenames contain no colons. Log contents are never copied into command output, diagnostics or the dashboard. The owner-private log is compacted after it exceeds 1.5 MiB and is trimmed to the most recent 1 MiB of stdout/stderr. Log open, write or close failures do not stop the instance: output that cannot be written is discarded, and list shows `EXTENSION_LOG_UNAVAILABLE` as an informational diagnostic. [CLI output](output.md) defines the separate execution-command records.
44
+ Handler errors, timeouts, crashes and backpressure disable the affected instance for the rest of the owning coordinator's lifetime; it is not automatically restarted. Its failure remains visible through list for that lifetime, including after explicit re-enablement starts a new instance. Restarting the coordinator resets runtime failure state. A stopped or unavailable coordinator cannot supply retained runtime diagnostics. Static discovery remains distinct from runtime status; uncertain communication is reported instead of presented as a healthy process. The CLI displays `EXTENSION_*` codes and their safe messages only through list; they also remain available through the coordinator's existing safe diagnostics. The dashboard does not display extension diagnostics. An unexpected extension-process exit uses `EXTENSION_EXITED` and disables the instance like other failures. Runtime diagnostics never expose event content, raw child output, thrown messages, stacks or credentials. List shows the actual log path: `<stateDirectory>/extensions/global-<id>.log` for a global instance or `<stateDirectory>/extensions/repo-<id>-<root-hash>.log` for a repository instance. `<root-hash>` is the first 12 hex characters of the SHA-256 of the canonical project-root path, so filenames contain no colons. Log contents are never copied into command output, diagnostics or the dashboard. The owner-private log is compacted after it exceeds 1.5 MiB and is trimmed to the most recent 1 MiB of stdout/stderr. Log open, write or close failures do not stop the instance: output that cannot be written is discarded, and list shows `EXTENSION_LOG_UNAVAILABLE` as an informational diagnostic. [CLI output](output.md) defines the separate execution-command records.
package/sdk/cli/index.md CHANGED
@@ -3,18 +3,20 @@
3
3
  The CLI is the primary execution interface for an everyday coding assistant. The assistant can invoke a native harness directly or a reusable specialist defined with the SDK, run commands through its host's background-task controls, and use identifiers for later interactions. `subharness` is the primary executable; `agent` is a compatibility alias with identical behavior.
4
4
 
5
5
  ```sh
6
- subharness list [--cwd <directory>]
6
+ subharness list [--root <directory>] [--cwd <directory>]
7
7
  subharness dashboard
8
8
  subharness extensions --help
9
- subharness extensions list
10
- subharness extensions enable <global:id|repo:id>
11
- subharness extensions disable <global:id|repo:id>
12
- subharness check <target> [--cwd <directory>] [--format text|jsonl]
13
- subharness check <harness> [--cwd <directory>] [--model <model>] [--effort <effort>] [--format text|jsonl]
14
- subharness run <target> [--cwd <directory>] [--detach] <prompt>
15
- subharness run <target> [--cwd <directory>] [--detach] --prompt <text>
16
- subharness run <target> [--cwd <directory>] [--detach] --prompt-file <path|->
17
- subharness run <harness> [--model <model>] [--effort <effort>] <prompt>
9
+ subharness extensions list [--root <directory>]
10
+ subharness extensions enable <global:id|repo:id> [--root <directory>]
11
+ subharness extensions disable <global:id|repo:id> [--root <directory>]
12
+ subharness check <target> [--root <directory>] [--cwd <directory>] [--format text|jsonl]
13
+ subharness check <definition.ts> [--root <directory>] [--cwd <directory>] [--format text|jsonl]
14
+ subharness check <harness> [--root <directory>] [--cwd <directory>] [--model <model>] [--effort <effort>] [--format text|jsonl]
15
+ subharness run <target> [--root <directory>] [--cwd <directory>] [--detach] <prompt>
16
+ subharness run <definition.ts> [--root <directory>] [--cwd <directory>] [--detach] <prompt>
17
+ subharness run <target> [--root <directory>] [--cwd <directory>] [--detach] --prompt <text>
18
+ subharness run <target> [--root <directory>] [--cwd <directory>] [--detach] --prompt-file <path|->
19
+ subharness run <harness> [--root <directory>] [--cwd <directory>] [--model <model>] [--effort <effort>] <prompt>
18
20
  subharness run <harness> --help
19
21
  subharness send <session-id> [--delivery queue|steer|interrupt] [--detach] <prompt>
20
22
  subharness send <session-id> [--delivery queue|steer|interrupt] [--detach] --prompt <text>
@@ -37,6 +39,18 @@ Readiness means only that startup checks for the selected target passed at that
37
39
 
38
40
  `run --detach` instead returns immediately after successful admission with only the same `started` record.
39
41
 
42
+ ## Select a project
43
+
44
+ `--root <directory>` selects a [logical project](../project-root.md) for `list`, `check`, `run`, and extension list/enable/disable. Relative roots resolve from the invoking directory. The selected project owns its repository agents, personal access, and extensions; enclosing catalogs and settings are not merged. An omitted `--cwd` defaults to that root. An explicit relative `--cwd` resolves independently from the invoking directory and changes execution only. Without `--root`, execution defaults to the invoking directory and discovery retains its Git-root rules.
45
+
46
+ ```sh
47
+ subharness list --root ./apps/my-app
48
+ subharness check --root ./apps/my-app repo:reviewer
49
+ subharness run --root ./apps/my-app repo:reviewer --prompt "Review this app."
50
+ ```
51
+
52
+ Linked worktrees share personal access at the corresponding app path in the main checkout. Definitions and extensions stay in the selected worktree app. Explicit-root runs and managed `list`, `check`, or `run` commands supplying `--root` require coordinator capability `cli-root-v1`; an older live coordinator yields `COORDINATOR_OUTDATED` before submission, with no automatic restart or default-root fallback. Top-level `list` and `check` remain coordinator-free. Session-ID commands retain the selected project and do not accept `--root`.
53
+
40
54
  ## Close a session
41
55
 
42
56
  `subharness close <session-id>` stops new admission to the session, cancels its active and queued tasks and their recorded descendants with confirmed-stop semantics, and then closes the native harness resources. The harness therefore performs cleanup for tool processes that it tracks as part of the native session. The closed session and its retained task records remain inspectable. Closing an already closed session succeeds.
@@ -49,7 +63,7 @@ Task cancellation and interrupt stop the agent's active native turn, including r
49
63
 
50
64
  Verification scope is limited to live Codex 0.157.0 and Claude Code 2.1.288 sessions plus fx 0.0.12 source inspection. The fx evidence is source-only because that installed version could not create a live session during verification. OpenCode, GitHub Copilot, and Cursor have no equivalent verified tool-process evidence; their adapter close contract still applies.
51
65
 
52
- [Extension commands](extensions.md) discover static manifests and manage explicit per-user consent in the owner-only `~/.subharness/extensions.json` file. `subharness extensions` without a subcommand prints extensions usage to stderr and exits `2`; `subharness extensions --help` prints it to stdout and exits `0`. These commands use text output, never import extension modules, and do not accept `--format`. The coordinator supervises each applicable extension in a separate child process when its first matching session is admitted. Newly admitted CLI and connected SDK sessions are assigned to enabled global extensions and enabled repository extensions for their checkout. The dashboard and embedded runners do not load extension code.
66
+ [Extension commands](extensions.md) discover static manifests and manage explicit per-user consent in the owner-only `~/.subharness/extensions.json` file. `subharness extensions` without a subcommand prints extensions usage to stderr and exits `2`; `subharness extensions --help` prints it to stdout and exits `0`. These commands use text output, never import extension modules, and do not accept `--format`. The coordinator supervises each applicable extension in a separate child process when its first matching session is admitted. Newly admitted CLI and connected SDK sessions are assigned to enabled global extensions and enabled repository extensions for their selected project root. Without `--root`, this retains the execution checkout scope; root-selected sessions use their logical project even when execution cwd is elsewhere. The dashboard and embedded runners do not load extension code.
53
67
 
54
68
  ## Live dashboard
55
69
 
@@ -77,6 +91,8 @@ The command requires terminal stdout and a terminal supporting cursor control; n
77
91
 
78
92
  ## Direct harnesses and specialists
79
93
 
94
+ `run` and `check` also accept an explicit `.ts` agent definition path, excluding `.d.ts` declarations. Paths resolve from the invoking command's directory, independently of `--cwd` and `--root`, and load only the selected definition and its imports. The definition can live inside a monorepo app without a root catalog entry. See [explicit definition files](../config.md#explicit-definition-files) for target recognition, validation, execution context, and managed-parent restrictions.
95
+
80
96
  `codex`, `claude`, `fx`, `opencode`, `copilot`, and `cursor` are reserved, case-sensitive target names for direct harness execution. `claude` selects the Claude Code adapter, whose SDK and access configuration key remains `claudeCode`. Direct execution needs its native runtime and eligible access, but no TypeScript definition, project-local SDK import, or agent catalog evaluation. An invalid specialist file does not block a direct harness run.
81
97
 
82
98
  ```sh
@@ -94,7 +110,7 @@ Replace `provider/model` or `creator/model` with an available Gateway model iden
94
110
 
95
111
  Direct harness sessions use native instructions and project context without adding a specialist role, custom tools, or declared children. They preserve the existing authentication, native permission, queue, cancellation, follow-up, and response contracts. They do not broaden the caller's native permissions or automatically authorize additional delegation.
96
112
 
97
- `--model` configures direct harness targets only for `run` and `check`, and can be combined with `--cwd` and, for `run`, any supported prompt source. `--effort` is additionally available for Codex, Claude Code, and fx. Empty values are errors. Specialist targets reject these overrides and retain their declared harness configurations. `send` retains the session configuration and does not accept model or effort overrides.
113
+ `--model` configures direct harness targets only for `run` and `check`, and can be combined with `--root`, `--cwd`, and, for `run`, any supported prompt source. `--effort` is additionally available for Codex, Claude Code, and fx. Empty values are errors. Specialist targets reject these overrides and retain their declared harness configurations. `send` retains the session configuration and does not accept model or effort overrides.
98
114
 
99
115
  For Codex, Claude Code, and fx, omitting `--model` requests the native default for the authorized access route at session creation. OpenCode, Copilot, and Cursor require an explicit `--model`; omission fails with `INVALID_CONFIG` and guidance before native startup. The adapter retains the selected model for that conversation. It does not inherit the calling agent's model, rank models, choose a substitute, or change billing routes. An unavailable or unverifiable native default fails with actionable guidance to supply `--model`; it does not submit a prompt merely to discover a default. Explicit model identifiers retain native validation and substitution checks. TypeScript harness constructors continue to require a model.
100
116
 
@@ -114,7 +130,7 @@ Callers that generate long or multiline prompts should use `--prompt-file <path>
114
130
 
115
131
  Generated long or multiline prompts should not be passed through `--prompt` or a positional argument. Large argument vectors increase process-launch cost, and a host argument limit can reject process launch with an explicit host error. Keeping the prompt payload out of the argument vector does not eliminate unrelated host resource pressure. If the host instead kills the CLI before admission, no task exists and the command prints nothing.
116
132
 
117
- `--prompt-file -` reads standard input to EOF. It is explicit: piped stdin is not read or appended when another prompt source is supplied. Interactive terminal stdin is rejected instead of waiting for a conversation. Missing, empty, invalid UTF-8, and oversized input fail before session admission. File and stdin diagnostics distinguish read failures from invalid UTF-8 content. Files and stdin are bounded while reading to 1 MiB. File paths resolve relative to the calling command's directory, independently of `--cwd`. Omitted `--cwd` uses the calling directory. Follow-ups retain their session's execution directory.
133
+ `--prompt-file -` reads standard input to EOF. It is explicit: piped stdin is not read or appended when another prompt source is supplied. Interactive terminal stdin is rejected instead of waiting for a conversation. Missing, empty, invalid UTF-8, and oversized input fail before session admission. File and stdin diagnostics distinguish read failures from invalid UTF-8 content. Files and stdin are bounded while reading to 1 MiB. File paths resolve relative to the calling command's directory, independently of `--cwd` and `--root`. Omitted `--cwd` uses an explicitly selected root, or the calling directory otherwise. Follow-ups retain their session's execution directory.
118
134
 
119
135
  `send` defaults to `queue`, creating a new task that waits for the active task's full completion boundary. `steer` targets whichever task is active when handled. If that task is between native turns, steering starts a continuation of the same task. If an actively generating harness lacks steering, the operation follows `interrupt` semantics and reports the effective mode. `interrupt` cancels affected work, waits for stop confirmation, and starts a replacement before independently queued tasks. See [message delivery](../message-delivery.md).
120
136
 
@@ -124,7 +140,7 @@ Native steering returns an acceptance acknowledgement. Queued and interrupting s
124
140
 
125
141
  ## Nested execution
126
142
 
127
- A managed agent invokes its own declared children with `subharness run subagent:<name>`. Parent context is supplied internally, not through public flags. Names resolve only against that parent's direct declarations. This invocation loads the parent's definition source without discovering unrelated repository or global entries, so an unrelated broken definition does not block a declared child. A generic parent has no declared children and fails this lookup without evaluating a specialist catalog. Missing context or an undeclared child is an error; there is no fallback to another scope. Child execution uses the same commands and lifecycle.
143
+ A managed agent invokes its own declared children with `subharness run subagent:<name>`. Parent context is supplied internally, not through public flags. Names resolve only against that parent's direct declarations in its captured definition graph. This invocation neither reloads the source nor discovers unrelated repository or global entries, so changed source files or an unrelated broken definition do not change a declared child. A generic parent has no declared children and fails this lookup without evaluating a specialist catalog. Missing context or an undeclared child is an error; there is no fallback to another scope. Child execution uses the same commands and lifecycle. An explicit project root and its access root are inherited transitively, independently of child execution cwd. Managed `list`, `run`, and `check` calls cannot supply `--root`, even to repeat the inherited value; after parent validation, it fails with `INVALID_ARGUMENT`. An omitted child `--cwd` keeps the invoking managed command's directory. Parents without an explicit root keep their existing cwd-based discovery rules.
128
144
 
129
145
  The caller supplies an existing working directory. The library does not create worktrees or sandboxes. A local coordinator owns pending execution after an individual response command exits. `--detach` releases only the CLI observation; it does not override process-lifecycle restrictions imposed by the host. Use host-owned background controls when the coordinator and workers must remain reachable after a shell command exits. Pending execution is not guaranteed to survive coordinator or environment exit, and detached admission does not promise automatic reactivation of an external parent chat.
130
146
 
package/sdk/cli/output.md CHANGED
@@ -18,7 +18,7 @@ A successful readiness check emits one record and admits no task:
18
18
  {"version":1,"type":"check","target":"repo:developer","ready":true}
19
19
  ```
20
20
 
21
- Text output is a short line identifying the ready target. A failed check emits the existing `error` record. Access and capability failures exit `1`; invalid arguments, configuration, or targets exit `2`.
21
+ Text output is a short line identifying the ready target. Control characters, DEL, and Unicode line separators in a target are escaped in text output so a file path cannot insert terminal controls or extra lines. The JSONL `target` retains the original argument as a JSON string. A failed check emits the existing `error` record. Access and capability failures exit `1`; invalid arguments, configuration, or targets exit `2`.
22
22
 
23
23
  Quiet tasks keep their local observation connection alive without printing progress messages or extra JSONL records. Transport keepalives are private to the CLI/coordinator connection. A lost observer connection does not cancel or replay its task; callers can retrieve its state and response with `status`.
24
24