@automatalabs/workflows 0.57.1 → 0.58.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -6
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +1 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/mcp-server.js +947 -93
- package/dist/validate.d.ts +2 -0
- package/dist/validate.d.ts.map +1 -1
- package/dist/validate.js +42 -15
- package/package.json +5 -5
package/dist/mcp-server.js
CHANGED
|
@@ -30646,9 +30646,9 @@ import {
|
|
|
30646
30646
|
buildModelFilter,
|
|
30647
30647
|
parseWorkflowScript,
|
|
30648
30648
|
probeHarnessConfig as probeHarnessConfig2,
|
|
30649
|
-
redactText as
|
|
30649
|
+
redactText as redactText3,
|
|
30650
30650
|
validateWorkflowScript,
|
|
30651
|
-
truncateUtf8 as
|
|
30651
|
+
truncateUtf8 as truncateUtf84,
|
|
30652
30652
|
workflowMayUseDefaultModel,
|
|
30653
30653
|
WorkflowError,
|
|
30654
30654
|
WorkflowErrorCode,
|
|
@@ -30661,6 +30661,12 @@ import {
|
|
|
30661
30661
|
|
|
30662
30662
|
// ../mcp-server/src/workflow-tool-input.ts
|
|
30663
30663
|
import { isAbsolute } from "node:path";
|
|
30664
|
+
var permissionResponseSchema = external_exports.object({
|
|
30665
|
+
outcome: external_exports.discriminatedUnion("outcome", [
|
|
30666
|
+
external_exports.object({ outcome: external_exports.literal("cancelled") }).strict(),
|
|
30667
|
+
external_exports.object({ outcome: external_exports.literal("selected"), optionId: external_exports.string().min(1).max(512) }).strict()
|
|
30668
|
+
])
|
|
30669
|
+
}).strict();
|
|
30664
30670
|
var checkpointRepliesSchema = external_exports.record(
|
|
30665
30671
|
external_exports.string().refine(
|
|
30666
30672
|
(key) => {
|
|
@@ -30672,17 +30678,17 @@ var checkpointRepliesSchema = external_exports.record(
|
|
|
30672
30678
|
external_exports.unknown()
|
|
30673
30679
|
);
|
|
30674
30680
|
var workflowToolInputShape = {
|
|
30675
|
-
action: external_exports.enum(["run", "config", "inspect", "await", "stop"]).optional().describe(
|
|
30676
|
-
"Operation. Omit or use run to validate then execute; config discovers live backend/model/mode/config options
|
|
30681
|
+
action: external_exports.enum(["run", "config", "inspect", "await", "stop", "permissions-response"]).optional().describe(
|
|
30682
|
+
"Operation. Omit or use run to validate then execute; config discovers live backend/model/mode/config options; inspect/await expose live action requirements; permissions-response resolves one pending ACP permission; stop aborts a run or one in-flight agent."
|
|
30677
30683
|
),
|
|
30678
30684
|
script: external_exports.string().min(1).optional().describe(
|
|
30679
|
-
"Raw JavaScript workflow script (no Markdown fences). Exactly one of script or scriptPath is required for run; both are forbidden for config/inspect/await/stop. First statement MUST be `export const meta = { name, description, phases? }`. When present, phases MUST be an array of objects shaped `{ title: string, detail?: string, model?: string }`, never an array of strings."
|
|
30685
|
+
"Raw JavaScript workflow script (no Markdown fences). Exactly one of script or scriptPath is required for run; both are forbidden for config/inspect/await/stop/permissions-response. First statement MUST be `export const meta = { name, description, phases? }`. When present, phases MUST be an array of objects shaped `{ title: string, detail?: string, model?: string }`, never an array of strings."
|
|
30680
30686
|
),
|
|
30681
30687
|
scriptPath: external_exports.string().min(1).refine((value) => isAbsolute(value), "scriptPath must be an absolute path").optional().describe(
|
|
30682
|
-
"Absolute path, on the server's filesystem, to a workflow script file read once at admission. Exactly one of script or scriptPath is required for run; both are forbidden for config/inspect/await/stop. Relative paths are rejected."
|
|
30688
|
+
"Absolute path, on the server's filesystem, to a workflow script file read once at admission. Exactly one of script or scriptPath is required for run; both are forbidden for config/inspect/await/stop/permissions-response. Relative paths are rejected."
|
|
30683
30689
|
),
|
|
30684
30690
|
projectDir: external_exports.string().min(1).refine((value) => isAbsolute(value), "projectDir must be an absolute path").optional().describe(
|
|
30685
|
-
"Absolute project directory used as the cwd for config discovery and, for run, the project-scoped store (where the runId, journal, and resume state live) plus default execution cwd. Required for run and config on the shared workflow daemon; on a single-project (in-process) server it defaults to that server's own project. Forbidden for inspect/await/stop \u2014 a runId locates its project."
|
|
30691
|
+
"Absolute project directory used as the cwd for config discovery and, for run, the project-scoped store (where the runId, journal, and resume state live) plus default execution cwd. Required for run and config on the shared workflow daemon; on a single-project (in-process) server it defaults to that server's own project. Forbidden for inspect/await/stop/permissions-response \u2014 a runId locates its project."
|
|
30686
30692
|
),
|
|
30687
30693
|
harnesses: external_exports.array(external_exports.string().regex(/^[a-z][a-z0-9._-]*$/i, "invalid backend name")).min(1).max(16).optional().describe('With action="config", backend names to probe. Omit to probe every backend registered on this server.'),
|
|
30688
30694
|
modelSpecs: external_exports.array(external_exports.string().min(1).max(256)).min(1).max(16).optional().describe(
|
|
@@ -30704,7 +30710,9 @@ var workflowToolInputShape = {
|
|
|
30704
30710
|
resumePolicy: external_exports.enum(["auto", "positional"]).optional().describe('Resume matching policy. Default "auto"; requires resumeFromRunId.'),
|
|
30705
30711
|
checkpointReplies: checkpointRepliesSchema.optional().describe("With resumeFromRunId, durable-checkpoint decisions keyed by checkpointContext.callIndex."),
|
|
30706
30712
|
background: external_exports.boolean().optional().describe("Default false. True acknowledges after admission and executes in this server process."),
|
|
30707
|
-
runId: external_exports.string().max(128).regex(/^[a-z0-9]+-[a-z0-9]+$/, "runId must be an engine-generated run ID").optional().describe("Project-scoped workflow run ID. Required for inspect/await/stop; forbidden for config/run."),
|
|
30713
|
+
runId: external_exports.string().max(128).regex(/^[a-z0-9]+-[a-z0-9]+$/, "runId must be an engine-generated run ID").optional().describe("Project-scoped workflow run ID. Required for inspect/await/stop/permissions-response; forbidden for config/run."),
|
|
30714
|
+
permissionId: external_exports.string().uuid().optional().describe('With action="permissions-response", the opaque pending permission id returned by inspect/await.'),
|
|
30715
|
+
response: permissionResponseSchema.optional().describe('With action="permissions-response", an exact ACP selected optionId or cancelled outcome.'),
|
|
30708
30716
|
callIndex: external_exports.number().int().nonnegative().safe().optional().describe(
|
|
30709
30717
|
"With action=stop, cancel exactly this in-flight agent call without aborting the run. Forbidden for every other action."
|
|
30710
30718
|
),
|
|
@@ -30721,6 +30729,9 @@ var workflowToolInputShape = {
|
|
|
30721
30729
|
function hasConfigFields(raw) {
|
|
30722
30730
|
return raw.harnesses !== void 0 || raw.modelSpecs !== void 0 || raw.modelFilter !== void 0 || raw.probeTimeoutMs !== void 0;
|
|
30723
30731
|
}
|
|
30732
|
+
function hasPermissionFields(raw) {
|
|
30733
|
+
return raw.permissionId !== void 0 || raw.response !== void 0;
|
|
30734
|
+
}
|
|
30724
30735
|
function hasExecutionFields(raw) {
|
|
30725
30736
|
return raw.script !== void 0 || raw.scriptPath !== void 0 || raw.projectDir !== void 0 || raw.args !== void 0 || raw.maxAgents !== void 0 || raw.concurrency !== void 0 || raw.agentRetries !== void 0 || raw.agentTimeoutMs !== void 0 || raw.agentIdleTimeoutMs !== void 0 || raw.resumeFromRunId !== void 0 || raw.resumePolicy !== void 0 || raw.checkpointReplies !== void 0 || raw.background !== void 0;
|
|
30726
30737
|
}
|
|
@@ -30729,7 +30740,7 @@ function invalid(message) {
|
|
|
30729
30740
|
}
|
|
30730
30741
|
function parseWorkflowToolInput(raw, options = {}) {
|
|
30731
30742
|
if (raw.action === "config") {
|
|
30732
|
-
if (raw.script !== void 0 || raw.scriptPath !== void 0 || raw.args !== void 0 || raw.maxAgents !== void 0 || raw.concurrency !== void 0 || raw.agentRetries !== void 0 || raw.agentTimeoutMs !== void 0 || raw.agentIdleTimeoutMs !== void 0 || raw.resumeFromRunId !== void 0 || raw.resumePolicy !== void 0 || raw.checkpointReplies !== void 0 || raw.background !== void 0 || raw.runId !== void 0 || raw.callIndex !== void 0 || raw.forceOwner !== void 0 || raw.waitMs !== void 0 || raw.lastN !== void 0 || raw.labelGlob !== void 0 || raw.logLines !== void 0) {
|
|
30743
|
+
if (raw.script !== void 0 || raw.scriptPath !== void 0 || raw.args !== void 0 || raw.maxAgents !== void 0 || raw.concurrency !== void 0 || raw.agentRetries !== void 0 || raw.agentTimeoutMs !== void 0 || raw.agentIdleTimeoutMs !== void 0 || raw.resumeFromRunId !== void 0 || raw.resumePolicy !== void 0 || raw.checkpointReplies !== void 0 || raw.background !== void 0 || raw.runId !== void 0 || hasPermissionFields(raw) || raw.callIndex !== void 0 || raw.forceOwner !== void 0 || raw.waitMs !== void 0 || raw.lastN !== void 0 || raw.labelGlob !== void 0 || raw.logLines !== void 0) {
|
|
30733
30744
|
invalid('action="config" accepts only projectDir, harnesses, modelSpecs, modelFilter, and probeTimeoutMs');
|
|
30734
30745
|
}
|
|
30735
30746
|
if (options.requireProjectDir === true && raw.projectDir === void 0) {
|
|
@@ -30746,9 +30757,24 @@ function parseWorkflowToolInput(raw, options = {}) {
|
|
|
30746
30757
|
probeTimeoutMs: raw.probeTimeoutMs
|
|
30747
30758
|
};
|
|
30748
30759
|
}
|
|
30760
|
+
if (raw.action === "permissions-response") {
|
|
30761
|
+
if (!raw.runId) invalid('action="permissions-response" requires runId');
|
|
30762
|
+
if (!raw.permissionId || raw.response === void 0) {
|
|
30763
|
+
invalid('action="permissions-response" requires permissionId and response');
|
|
30764
|
+
}
|
|
30765
|
+
if (hasExecutionFields(raw) || hasConfigFields(raw) || raw.waitMs !== void 0 || raw.callIndex !== void 0 || raw.forceOwner !== void 0 || raw.lastN !== void 0 || raw.labelGlob !== void 0 || raw.logLines !== void 0) {
|
|
30766
|
+
invalid('action="permissions-response" accepts only runId, permissionId, and response');
|
|
30767
|
+
}
|
|
30768
|
+
return {
|
|
30769
|
+
action: "permissions-response",
|
|
30770
|
+
runId: raw.runId,
|
|
30771
|
+
permissionId: raw.permissionId,
|
|
30772
|
+
response: raw.response
|
|
30773
|
+
};
|
|
30774
|
+
}
|
|
30749
30775
|
if (raw.action === "inspect") {
|
|
30750
30776
|
if (!raw.runId) invalid('action="inspect" requires runId');
|
|
30751
|
-
if (hasExecutionFields(raw) || hasConfigFields(raw) || raw.waitMs !== void 0 || raw.callIndex !== void 0 || raw.forceOwner !== void 0) {
|
|
30777
|
+
if (hasExecutionFields(raw) || hasConfigFields(raw) || hasPermissionFields(raw) || raw.waitMs !== void 0 || raw.callIndex !== void 0 || raw.forceOwner !== void 0) {
|
|
30752
30778
|
invalid('action="inspect" cannot include execution fields');
|
|
30753
30779
|
}
|
|
30754
30780
|
return {
|
|
@@ -30761,7 +30787,7 @@ function parseWorkflowToolInput(raw, options = {}) {
|
|
|
30761
30787
|
}
|
|
30762
30788
|
if (raw.action === "await") {
|
|
30763
30789
|
if (!raw.runId) invalid('action="await" requires runId');
|
|
30764
|
-
if (hasExecutionFields(raw) || hasConfigFields(raw) || raw.callIndex !== void 0 || raw.forceOwner !== void 0) {
|
|
30790
|
+
if (hasExecutionFields(raw) || hasConfigFields(raw) || hasPermissionFields(raw) || raw.callIndex !== void 0 || raw.forceOwner !== void 0) {
|
|
30765
30791
|
invalid('action="await" cannot include execution fields');
|
|
30766
30792
|
}
|
|
30767
30793
|
return {
|
|
@@ -30775,7 +30801,7 @@ function parseWorkflowToolInput(raw, options = {}) {
|
|
|
30775
30801
|
}
|
|
30776
30802
|
if (raw.action === "stop") {
|
|
30777
30803
|
if (!raw.runId) invalid('action="stop" requires runId');
|
|
30778
|
-
if (hasExecutionFields(raw) || hasConfigFields(raw) || raw.waitMs !== void 0) {
|
|
30804
|
+
if (hasExecutionFields(raw) || hasConfigFields(raw) || hasPermissionFields(raw) || raw.waitMs !== void 0) {
|
|
30779
30805
|
invalid('action="stop" cannot include execution fields or waitMs');
|
|
30780
30806
|
}
|
|
30781
30807
|
if (raw.callIndex !== void 0 && raw.forceOwner !== void 0) {
|
|
@@ -30791,7 +30817,7 @@ function parseWorkflowToolInput(raw, options = {}) {
|
|
|
30791
30817
|
logLines: raw.logLines
|
|
30792
30818
|
};
|
|
30793
30819
|
}
|
|
30794
|
-
if (raw.runId !== void 0 || raw.callIndex !== void 0 || raw.forceOwner !== void 0 || raw.waitMs !== void 0 || raw.lastN !== void 0 || raw.labelGlob !== void 0 || raw.logLines !== void 0 || hasConfigFields(raw)) {
|
|
30820
|
+
if (raw.runId !== void 0 || hasPermissionFields(raw) || raw.callIndex !== void 0 || raw.forceOwner !== void 0 || raw.waitMs !== void 0 || raw.lastN !== void 0 || raw.labelGlob !== void 0 || raw.logLines !== void 0 || hasConfigFields(raw)) {
|
|
30795
30821
|
invalid("run inputs cannot include inspection fields");
|
|
30796
30822
|
}
|
|
30797
30823
|
const hasScript = raw.script !== void 0;
|
|
@@ -31667,6 +31693,44 @@ var authContextSchema = external_exports.object({
|
|
|
31667
31693
|
external_exports.object({ id: external_exports.string(), type: external_exports.enum(["agent", "terminal"]), name: external_exports.string().optional() })
|
|
31668
31694
|
)
|
|
31669
31695
|
});
|
|
31696
|
+
var permissionOutcomeSchema = external_exports.discriminatedUnion("outcome", [
|
|
31697
|
+
external_exports.object({ outcome: external_exports.literal("cancelled") }).strict(),
|
|
31698
|
+
external_exports.object({ outcome: external_exports.literal("selected"), optionId: external_exports.string() }).strict()
|
|
31699
|
+
]);
|
|
31700
|
+
var pendingPermissionSchema = external_exports.object({
|
|
31701
|
+
version: external_exports.literal(1),
|
|
31702
|
+
permissionId: external_exports.string().uuid(),
|
|
31703
|
+
runId: external_exports.string(),
|
|
31704
|
+
callIndex: external_exports.number().int().nonnegative(),
|
|
31705
|
+
backendId: external_exports.string(),
|
|
31706
|
+
label: external_exports.string().optional(),
|
|
31707
|
+
requestedAt: external_exports.string(),
|
|
31708
|
+
request: external_exports.object({
|
|
31709
|
+
toolCall: external_exports.record(external_exports.string(), external_exports.unknown()),
|
|
31710
|
+
options: external_exports.array(external_exports.object({
|
|
31711
|
+
optionId: external_exports.string(),
|
|
31712
|
+
name: external_exports.string(),
|
|
31713
|
+
kind: external_exports.string(),
|
|
31714
|
+
_meta: external_exports.record(external_exports.string(), external_exports.unknown()).nullable().optional()
|
|
31715
|
+
})),
|
|
31716
|
+
_meta: external_exports.record(external_exports.string(), external_exports.unknown()).nullable().optional()
|
|
31717
|
+
}),
|
|
31718
|
+
requestTruncated: external_exports.boolean(),
|
|
31719
|
+
requestRedacted: external_exports.boolean()
|
|
31720
|
+
});
|
|
31721
|
+
var permissionInteractionSchema = external_exports.object({
|
|
31722
|
+
permissionRequests: external_exports.literal("may-block"),
|
|
31723
|
+
collectWith: external_exports.array(external_exports.enum(["await", "inspect"])),
|
|
31724
|
+
respondWith: external_exports.literal("permissions-response"),
|
|
31725
|
+
elicitation: external_exports.enum(["available", "unavailable"])
|
|
31726
|
+
});
|
|
31727
|
+
var permissionAcknowledgementSchema = external_exports.object({
|
|
31728
|
+
permissionId: external_exports.string().uuid(),
|
|
31729
|
+
runId: external_exports.string(),
|
|
31730
|
+
callIndex: external_exports.number().int().nonnegative(),
|
|
31731
|
+
outcome: permissionOutcomeSchema,
|
|
31732
|
+
respondedAt: external_exports.string()
|
|
31733
|
+
});
|
|
31670
31734
|
var checkpointContextSchema = external_exports.object({
|
|
31671
31735
|
callIndex: external_exports.number().int().nonnegative(),
|
|
31672
31736
|
hash: external_exports.string(),
|
|
@@ -31924,7 +31988,7 @@ var executionResultSchema = external_exports.object({
|
|
|
31924
31988
|
var waitSchema = external_exports.object({
|
|
31925
31989
|
requestedMs: external_exports.number().int().nonnegative(),
|
|
31926
31990
|
elapsedMs: external_exports.number().int().nonnegative(),
|
|
31927
|
-
returnedBecause: external_exports.enum(["terminal", "timeout", "immediate"])
|
|
31991
|
+
returnedBecause: external_exports.enum(["terminal", "timeout", "immediate", "action-required", "permission-resolved"])
|
|
31928
31992
|
});
|
|
31929
31993
|
var diagnosticRecordSchema = external_exports.record(external_exports.string(), external_exports.unknown());
|
|
31930
31994
|
var sessionModeStateSchema = external_exports.object({
|
|
@@ -31939,6 +32003,9 @@ var sessionModeStateSchema = external_exports.object({
|
|
|
31939
32003
|
});
|
|
31940
32004
|
var harnessDiagnosticSchema = external_exports.object({
|
|
31941
32005
|
backendId: external_exports.string(),
|
|
32006
|
+
defaultModeId: external_exports.string().optional().describe(
|
|
32007
|
+
"AgentPrism's explicit mode when a call omits mode; absent for no-mode/custom backends."
|
|
32008
|
+
),
|
|
31942
32009
|
model: external_exports.string().optional(),
|
|
31943
32010
|
probed: external_exports.boolean(),
|
|
31944
32011
|
error: external_exports.string().optional(),
|
|
@@ -32049,6 +32116,9 @@ var variantOutputFields = [
|
|
|
32049
32116
|
"stopped",
|
|
32050
32117
|
"alreadyTerminal",
|
|
32051
32118
|
"control",
|
|
32119
|
+
"pendingPermissions",
|
|
32120
|
+
"interaction",
|
|
32121
|
+
"permissionResponse",
|
|
32052
32122
|
...discoveryOutputFields
|
|
32053
32123
|
];
|
|
32054
32124
|
var forbidsRequired = (...fields) => ({
|
|
@@ -32091,7 +32161,10 @@ var workflowToolOutputShape = external_exports.object({
|
|
|
32091
32161
|
outcome: executionResultSchema.optional(),
|
|
32092
32162
|
stopped: external_exports.boolean().optional(),
|
|
32093
32163
|
alreadyTerminal: external_exports.boolean().optional(),
|
|
32094
|
-
control: stopControlSchema.optional()
|
|
32164
|
+
control: stopControlSchema.optional(),
|
|
32165
|
+
pendingPermissions: external_exports.array(pendingPermissionSchema).optional(),
|
|
32166
|
+
interaction: permissionInteractionSchema.optional(),
|
|
32167
|
+
permissionResponse: permissionAcknowledgementSchema.optional()
|
|
32095
32168
|
}).superRefine((value, context) => {
|
|
32096
32169
|
const has = (field) => value[field] !== void 0;
|
|
32097
32170
|
const inspectionComplete = inspectionRequired.every((field) => has(field));
|
|
@@ -32103,15 +32176,17 @@ var workflowToolOutputShape = external_exports.object({
|
|
|
32103
32176
|
} else if (value.action === "run") {
|
|
32104
32177
|
valid = value.status === "rejected" && has("validation") && hasOnlyExactFields(value, ["action", "status", "validation"]);
|
|
32105
32178
|
} else if (has("scriptSource")) {
|
|
32106
|
-
valid = runCommonComplete && has("limits") && (value.status === "running" ? hasOnlyFields(value, ["scriptSource"]) : terminal2 && hasOnlyFields(value, ["scriptSource", ...executionDetailFields]));
|
|
32179
|
+
valid = runCommonComplete && has("limits") && (value.status === "running" ? hasOnlyFields(value, ["scriptSource", "pendingPermissions", "interaction"]) : terminal2 && hasOnlyFields(value, ["scriptSource", ...executionDetailFields]));
|
|
32180
|
+
} else if (has("permissionResponse")) {
|
|
32181
|
+
valid = runCommonComplete && inspectionComplete && hasOnlyFields(value, [...inspectionFields, "pendingPermissions", "interaction", "permissionResponse"]);
|
|
32107
32182
|
} else if (has("control")) {
|
|
32108
32183
|
valid = runCommonComplete && inspectionComplete && value.stopped === false && value.alreadyTerminal === false && (value.status === "pending" || value.status === "running") && hasOnlyFields(value, [...inspectionFields, "stopped", "alreadyTerminal", "control"]);
|
|
32109
32184
|
} else if (has("stopped") || has("alreadyTerminal")) {
|
|
32110
32185
|
valid = runCommonComplete && inspectionComplete && has("stopped") && has("alreadyTerminal") && (value.status === "completed" || value.status === "failed" || value.status === "aborted") && hasOnlyFields(value, [...inspectionFields, "stopped", "alreadyTerminal"]);
|
|
32111
32186
|
} else if (has("wait")) {
|
|
32112
|
-
valid = runCommonComplete && inspectionComplete && hasOnlyFields(value, [...inspectionFields, "wait", "tokenUsage", "outcome"]) && (terminal2 ? has("outcome") : !has("outcome"));
|
|
32187
|
+
valid = runCommonComplete && inspectionComplete && hasOnlyFields(value, [...inspectionFields, "wait", "tokenUsage", "outcome", "pendingPermissions", "interaction"]) && (terminal2 ? has("outcome") : !has("outcome"));
|
|
32113
32188
|
} else {
|
|
32114
|
-
valid = runCommonComplete && inspectionComplete && hasOnlyFields(value, inspectionFields);
|
|
32189
|
+
valid = runCommonComplete && inspectionComplete && hasOnlyFields(value, [...inspectionFields, "pendingPermissions", "interaction"]);
|
|
32115
32190
|
}
|
|
32116
32191
|
if (!valid) {
|
|
32117
32192
|
context.addIssue({ code: "custom", message: "output does not match a workflow result variant" });
|
|
@@ -32168,17 +32243,17 @@ var workflowToolOutputShape = external_exports.object({
|
|
|
32168
32243
|
title: "Workflow background admission",
|
|
32169
32244
|
required: [...runOutputRequired, "scriptSource", "limits"],
|
|
32170
32245
|
properties: { status: { const: "running" } },
|
|
32171
|
-
...forbidsOutside(["scriptSource"])
|
|
32246
|
+
...forbidsOutside(["scriptSource", "pendingPermissions", "interaction"])
|
|
32172
32247
|
},
|
|
32173
32248
|
{
|
|
32174
32249
|
title: "Workflow inspection",
|
|
32175
32250
|
required: [...runOutputRequired, ...inspectionRequired],
|
|
32176
|
-
...forbidsOutside(inspectionFields)
|
|
32251
|
+
...forbidsOutside([...inspectionFields, "pendingPermissions", "interaction"])
|
|
32177
32252
|
},
|
|
32178
32253
|
{
|
|
32179
32254
|
title: "Workflow await",
|
|
32180
32255
|
required: [...runOutputRequired, ...inspectionRequired, "wait"],
|
|
32181
|
-
...forbidsOutside([...inspectionFields, "wait", "tokenUsage", "outcome"]),
|
|
32256
|
+
...forbidsOutside([...inspectionFields, "wait", "tokenUsage", "outcome", "pendingPermissions", "interaction"]),
|
|
32182
32257
|
anyOf: [
|
|
32183
32258
|
{
|
|
32184
32259
|
required: ["outcome"],
|
|
@@ -32190,6 +32265,11 @@ var workflowToolOutputShape = external_exports.object({
|
|
|
32190
32265
|
}
|
|
32191
32266
|
]
|
|
32192
32267
|
},
|
|
32268
|
+
{
|
|
32269
|
+
title: "Workflow permission response acknowledgement",
|
|
32270
|
+
required: [...runOutputRequired, ...inspectionRequired, "permissionResponse"],
|
|
32271
|
+
...forbidsOutside([...inspectionFields, "pendingPermissions", "interaction", "permissionResponse"])
|
|
32272
|
+
},
|
|
32193
32273
|
{
|
|
32194
32274
|
title: "Workflow stop acknowledgement",
|
|
32195
32275
|
required: [...runOutputRequired, ...inspectionRequired, "stopped", "alreadyTerminal"],
|
|
@@ -32413,7 +32493,7 @@ ${trimmed}` : "## Next step\n\nAuthor the workflow script the user asks for, the
|
|
|
32413
32493
|
"",
|
|
32414
32494
|
"Use the connected `docs` tool for version-matched authoring guidance. Read topic `workflow/quickstart` first, then read only the related workflow topics needed for this task; do not load every topic. Workflow scripts and REPL evals have different `agent()` signatures, so use only `workflow/*` topics here.",
|
|
32415
32495
|
"",
|
|
32416
|
-
'When the script pins a model, mode, or configOptions, call the `workflow` tool with `action:"config"` first; after choosing a model, use `modelSpecs` to read its exact option domain.
|
|
32496
|
+
'When the script pins a model, mode, or configOptions, call the `workflow` tool with `action:"config"` first; after choosing a model, use `modelSpecs` to read its exact option domain. Read the harness-owned mode names and descriptions before pinning an exact advertised id. Omission uses the reported `defaultModeId` (Claude auto, Codex agent, OpenCode build; none for Pi). The run action automatically performs static validation, a mocked dry run, and routed no-prompt config checks before admission. Correct any direct rejection diagnostic and re-run.',
|
|
32417
32497
|
"",
|
|
32418
32498
|
taskSection,
|
|
32419
32499
|
""
|
|
@@ -32470,9 +32550,9 @@ var AUTHORING_DOC_TOPICS = [
|
|
|
32470
32550
|
"workflow/run-lifecycle",
|
|
32471
32551
|
"workflow/examples"
|
|
32472
32552
|
],
|
|
32473
|
-
"bytes":
|
|
32474
|
-
"sha256": "
|
|
32475
|
-
"text": '# Workflow scripts: quickstart\n\n**Context:** JavaScript passed to the MCP `workflow` tool. This is not REPL code: workflow scripts use `agent(prompt, options?)`, allow top-level `return`, and start from a required metadata export.\n\nA workflow script is a deterministic orchestrator. Script code owns loops, fan-out, conditionals, aggregation, and checkpoints; `agent()` workers perform repository or research tasks. Workers start fresh sessions and do not share memory, so interpolate every prior result a later worker needs into its prompt.\n\n## Minimal valid script\n\n```js\nexport const meta = {\n name: "review-target",\n description: "Review a target and return concrete findings",\n phases: [{ title: "Review" }],\n};\n\nphase("Review");\nconst report = await agent(\n `Review ${args.target}. Read the relevant files and report concrete findings.`,\n { label: "review" },\n);\nreturn { report };\n```\n\nThe metadata export must be the first statement and a pure object literal. `name` and `description` are required non-empty strings. `phases`, when present, is an array of objects shaped `{ title: string, detail?: string, model?: string }`, never strings.\n\nSubmit the source without Markdown fences using the `workflow` tool\'s run form, with an absolute `projectDir` on the shared daemon. `args` is the JSON value supplied by the tool call. Some hosts may carry caller data as a JSON string, so harden scripts that accept external input:\n\n```js\nconst raw = typeof args === "string" ? (() => {\n try { return JSON.parse(args); } catch { return {}; }\n})() : args;\nconst input = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};\n```\n\n## Core rules\n\n- The DSL primitives are injected globals; do not import them.\n- Top-level `await` and top-level `return` are supported.\n- Scripts are JavaScript, not TypeScript.\n- No `require`, imports, filesystem API, network API, timers, `Date.now()`, `Math.random()`, or no-argument `Date` construction. Pass nondeterministic values through `args`.\n- Every `agent()` call should have a stable descriptive `label`.\n- A recoverable worker failure resolves to `null` after retries. Null-check load-bearing results.\n- `parallel()` takes thunks, not already-started promises:\n\n```js\nconst results = (await parallel([\n () => agent("Review correctness", { label: "review:correctness" }),\n () => agent("Review test coverage", { label: "review:coverage" }),\n])).filter(Boolean);\n```\n\n- Use a plain JSON Schema object in `schema` when script control flow depends on a worker result.\n- Return a compact JSON-serializable result; do not return a transcript.\n\n## Model selection\n\nOmit `model` for the server default, or use a backend-only value such as `"codex"` to retain that backend\'s configured default model. When `AGENTPRISM_DEFAULT_BACKEND` is truly unset, the MCP server probes backend readiness without prompting, pins one project default before validation/execution, and keeps that backend for the run and resume; an explicit environment default always wins. Before pinning a model id, `mode`, or `configOptions`, call `workflow` with `action:"config"`. After choosing a model, use `modelSpecs` to read that exact model\'s option domain.
|
|
32553
|
+
"bytes": 4254,
|
|
32554
|
+
"sha256": "49d4980013555baf3306eee64ae86e26eec2a45cfa352b130cf3862955199ae2",
|
|
32555
|
+
"text": '# Workflow scripts: quickstart\n\n**Context:** JavaScript passed to the MCP `workflow` tool. This is not REPL code: workflow scripts use `agent(prompt, options?)`, allow top-level `return`, and start from a required metadata export.\n\nA workflow script is a deterministic orchestrator. Script code owns loops, fan-out, conditionals, aggregation, and checkpoints; `agent()` workers perform repository or research tasks. Workers start fresh sessions and do not share memory, so interpolate every prior result a later worker needs into its prompt.\n\n## Minimal valid script\n\n```js\nexport const meta = {\n name: "review-target",\n description: "Review a target and return concrete findings",\n phases: [{ title: "Review" }],\n};\n\nphase("Review");\nconst report = await agent(\n `Review ${args.target}. Read the relevant files and report concrete findings.`,\n { label: "review" },\n);\nreturn { report };\n```\n\nThe metadata export must be the first statement and a pure object literal. `name` and `description` are required non-empty strings. `phases`, when present, is an array of objects shaped `{ title: string, detail?: string, model?: string }`, never strings.\n\nSubmit the source without Markdown fences using the `workflow` tool\'s run form, with an absolute `projectDir` on the shared daemon. `args` is the JSON value supplied by the tool call. Some hosts may carry caller data as a JSON string, so harden scripts that accept external input:\n\n```js\nconst raw = typeof args === "string" ? (() => {\n try { return JSON.parse(args); } catch { return {}; }\n})() : args;\nconst input = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};\n```\n\n## Core rules\n\n- The DSL primitives are injected globals; do not import them.\n- Top-level `await` and top-level `return` are supported.\n- Scripts are JavaScript, not TypeScript.\n- No `require`, imports, filesystem API, network API, timers, `Date.now()`, `Math.random()`, or no-argument `Date` construction. Pass nondeterministic values through `args`.\n- Every `agent()` call should have a stable descriptive `label`.\n- A recoverable worker failure resolves to `null` after retries. Null-check load-bearing results.\n- `parallel()` takes thunks, not already-started promises:\n\n```js\nconst results = (await parallel([\n () => agent("Review correctness", { label: "review:correctness" }),\n () => agent("Review test coverage", { label: "review:coverage" }),\n])).filter(Boolean);\n```\n\n- Use a plain JSON Schema object in `schema` when script control flow depends on a worker result.\n- Return a compact JSON-serializable result; do not return a transcript.\n\n## Model selection\n\nOmit `model` for the server default, or use a backend-only value such as `"codex"` to retain that backend\'s configured default model. When `AGENTPRISM_DEFAULT_BACKEND` is truly unset, the MCP server probes backend readiness without prompting, pins one project default before validation/execution, and keeps that backend for the run and resume; an explicit environment default always wins. Before pinning a model id, `mode`, or `configOptions`, call `workflow` with `action:"config"`. After choosing a model, use `modelSpecs` to read that exact model\'s option domain. Config preserves each advertised mode\'s id, name, description, and `_meta`, plus `defaultModeId`. When mode is omitted, AgentPrism applies Claude `auto`, Codex `agent`, OpenCode `build`, or no Pi mode. Pin only exact advertised ids and never guess model or option ids.\n\n## Validation and execution\n\nEvery run is statically parsed, mock-executed, and checked against no-prompt backend configuration before admission. A rejection creates no run ID, reserves no background slot, and spends no tokens. Read the diagnostic, correct the script, and submit it again.\n\nUse foreground execution for short work. Use `background:true` for work that may outlive one tool request; retain the returned `runId`, then use bounded `await`, `inspect`, or `stop` calls.\n\n## What to read next\n\n- `workflow/composition-and-failure` \u2014 metadata, fan-out, phases, and null semantics.\n- `workflow/api-agents` \u2014 every `agent()` option and structured output.\n- `workflow/run-lifecycle` \u2014 config, run, await, inspect, stop, and resume.\n- `workflow/examples` \u2014 complete composition patterns.\n'
|
|
32476
32556
|
},
|
|
32477
32557
|
{
|
|
32478
32558
|
"id": "workflow/run-lifecycle",
|
|
@@ -32485,9 +32565,9 @@ var AUTHORING_DOC_TOPICS = [
|
|
|
32485
32565
|
"workflow/determinism-and-resume",
|
|
32486
32566
|
"workflow/models-and-config"
|
|
32487
32567
|
],
|
|
32488
|
-
"bytes":
|
|
32489
|
-
"sha256": "
|
|
32490
|
-
"text": '## Running workflows \u2014 the MCP `workflow` tool\n\n**Context:** JavaScript passed to the MCP `workflow` tool. Workflow scripts use `agent(prompt, options?)`; REPL evals use a different API.\n\nUse the connected `workflow` tool for deterministic batch orchestration. The shared server daemon owns execution, so admitted runs survive MCP client session churn and tool-request timeouts. During a version upgrade, the successor becomes the front door while a predecessor may remain the execution owner; signed run-control forwarding keeps later-session stop/cancel operations location-independent. Owner-process exit can still interrupt in-flight work. Any later session can await, inspect, or stop a run. Runs, journals, logs, and outstanding whole-stop intents persist per project namespace.\n\nEvery `config` and `run` call on the shared daemon names its project with the required `projectDir` argument \u2014 an absolute path, normally the workspace root. `inspect`/`await`/`stop` take only a `runId`; the run ID locates its project store automatically. In a single-project server, `projectDir` defaults to that server\'s project.\n\n### The `workflow` tool, by action\n\n- **Config** (`{ action: "config", projectDir, harnesses?, modelSpecs?, modelFilter? }`): discover live model, mode, effort, and `configOptions` values from no-prompt backend sessions. Use `harnesses` plus `modelFilter` to find ids, then `modelSpecs` to select exact models and read their model-specific option domains. Each successful entry reports `
|
|
32568
|
+
"bytes": 8883,
|
|
32569
|
+
"sha256": "1f317847a48fa7ace2087677c818c57bb9dc7549cfc449e17703fe7636dd37f6",
|
|
32570
|
+
"text": '## Running workflows \u2014 the MCP `workflow` tool\n\n**Context:** JavaScript passed to the MCP `workflow` tool. Workflow scripts use `agent(prompt, options?)`; REPL evals use a different API.\n\nUse the connected `workflow` tool for deterministic batch orchestration. The shared server daemon owns execution, so admitted runs survive MCP client session churn and tool-request timeouts. During a version upgrade, the successor becomes the front door while a predecessor may remain the execution owner; signed run-control forwarding keeps later-session stop/cancel operations location-independent. Owner-process exit can still interrupt in-flight work. Any later session can await, inspect, or stop a run. Runs, journals, logs, and outstanding whole-stop intents persist per project namespace.\n\nEvery `config` and `run` call on the shared daemon names its project with the required `projectDir` argument \u2014 an absolute path, normally the workspace root. `inspect`/`await`/`stop` take only a `runId`; the run ID locates its project store automatically. In a single-project server, `projectDir` defaults to that server\'s project.\n\n### The `workflow` tool, by action\n\n- **Config** (`{ action: "config", projectDir, harnesses?, modelSpecs?, modelFilter? }`): discover live model, mode, effort, and `configOptions` values from no-prompt backend sessions. Use `harnesses` plus `modelFilter` to find ids, then `modelSpecs` to select exact models and read their model-specific option domains. Each successful entry preserves every harness-advertised mode id, name, description, and `_meta`, and reports `defaultModeId`. When a call omits mode, AgentPrism applies Claude `auto`, Codex `agent`, OpenCode `build`, or no mode for Pi; authored and default ids must appear in `modes.availableModes`. It starts no workflow and spends zero tokens. Use it only when pinning those values; an omitted model or backend-only model uses configured defaults without discovery.\n- **Run** (default, no `action`): supply exactly one of `script` (the raw source string, no Markdown fences) or `scriptPath` (an absolute path on the server\'s filesystem), plus `projectDir`. The tool automatically performs static validation, a mocked dry run, and routed config checks before admission. Invalid scripts return bounded `status:"rejected"` diagnostics with no run ID, background slot, or token spend. A path is read once at admission and its content snapshotted; later edits affect only a new run. `args` arrives in the script as the `args` global; the run\'s base directory is the `cwd` global. Some hosts hand `args` through as a JSON **string** \u2014 tolerate both shapes (`typeof args === "string" ? JSON.parse(args) : args`). Foreground streams progress but is bound to the request and its timeout. Pass `background: true` for anything that may outlive one request; it acknowledges after durable admission with a `runId`.\n- **Await** (`{ action: "await", runId, waitMs }`): bounded collection for background runs. A timeout is progress, not failure. Await returns early with `wait.returnedBecause:"action-required"` when an ACP permission is pending. At terminal status the response adds `outcome`: the authored result or pause context, plus replay diagnostics.\n- **Inspect** (`{ action: "inspect", runId, lastN, labelGlob, logLines }`): a bounded snapshot \u2014 the latest matching calls, newest log lines, and any live `pendingPermissions`. Elicitation-capable clients present one request\'s exact backend options during inspect/await. Permission diagnostics omit the private ACP session id, are credential-redacted and bounded, and retain the complete ordered exact option-id list or fail closed.\n- **Permission response** (`{ action:"permissions-response", runId, permissionId, response }`): for clients without elicitation, resolve one pending request with `{ outcome:{ outcome:"selected", optionId } }` using an exact advertised id, or `{ outcome:{ outcome:"cancelled" } }`. Caller-supplied response `_meta` is forbidden; provider effects come only from the selected advertised option. The request belongs to the live execution owner and cannot be answered after owner loss.\n- **Stop**: `{ action: "stop", runId }` durably aborts the whole run and normally returns its final snapshot; stopping a terminal run is a successful no-op. Across a daemon upgrade, the successor persists an idempotent stop intent and forwards to the predecessor that owns execution. If that owner does not settle within the bounded control wait, the successful response remains nonterminal with `control:{ state:"pending", operationId, requestedAt, owner? }`; retry stop, inspect, or await to observe settlement. `{ action: "stop", runId, callIndex }` synchronously routes to the live owner and cancels exactly that in-flight agent: its slot settles to `null` with `AGENT_CANCELLED` and the run stays live; call cancellation is never reconstructed after owner loss. Whole-run `{ action:"stop", runId, forceOwner:true }` explicitly authorizes terminating a superseded owner daemon when graceful control cannot settle and may interrupt sibling runs in that process; it is forbidden with `callIndex`. `labelGlob` only filters the returned snapshot; it never selects what to cancel.\n- **Resume**: a NEW run with `resumeFromRunId` plus the script content re-sent (the same `script` or `scriptPath`) and the desired `args` (+ `checkpointReplies` when answering a durable checkpoint). Read the returned `replayEligibility` for the predicted and observed replay prefix; never assume a prefix hit. Full semantics: **Determinism and resume**.\n\n### Operating rules\n\n- **Always retain the returned `runId`.** A paused, failed, or aborted response carries a redacted final-20 `logTail`. Read it before you change anything. Every admitted script is also an immutable resource at `workflow://runs/{runId}/script`, so a later session can recover a lost inline script.\n- **Two fingerprints control replay.** The identity hash covers the prompt, the resolved model, `mode` when set, non-empty sorted `configOptions`, `tier`, `phase`, `agentType`, the resolved agent definition, and the schema. The input fingerprint covers the resolved label, per-call `cwd` and isolation, `keepSession`, images, MCP servers, session/prompt metadata, and the approved script-backend digest.\n- **Operational bounds are not replay inputs.** Host `concurrency`, `agentRetries`, `agentTimeoutMs`, and `agentIdleTimeoutMs`, plus per-call `timeoutMs`, `idleTimeoutMs`, and `retries`, enter neither fingerprint. A resume does not inherit them from its source run; pass the values you want on every run. `agentTimeoutMs` caps total wall time and is not an idle timer. The separate opt-in `agentIdleTimeoutMs` fires after that long without real backend activity; ACP `session/update` re-arms it and synthetic progress heartbeats do not. Per-call values can tighten but cannot escape finite host ceilings. Every retry gets fresh clocks.\n- **Old journals stay usable.** Input formats below 2 replay positionally with `fallbackReason: "inputs-format-legacy"`. A current-format crash snapshot uses identity matching even without terminal-environment capture. Ancestor-scoped rows carried from \u22640.23 resume chains replay only while that ancestor run is still persisted. Journals resume across filesystem, environment, engine, Node, and V8 changes; `replayEligibility` reports those differences as diagnostics, never as gates.\n- **A background start returns immediately.** It sends no progress after it returns; collect progress with later bounded awaits. Its `interaction` block explains that ACP permissions may block an agent and names await/inspect plus `permissions-response` as the control path. Background runs have no live checkpoint channel, so authored `headless` checkpoint modes apply. When a run\'s owner process dies, a pending whole-stop intent is applied under the reclaimed lease; otherwise cold preflights reconcile stale `pending`/`running` state to `paused` with `pauseReason:"interrupted"`. A live owner lease is never stolen because of a timeout.\n- A run paused with `reason: "auth_required"` resumes as a new run after that backend\'s credentials are configured.\n\n### Execution logs \u2014 the events resource\n\nEvery journaling run publishes an MCP resource at `workflow://runs/{runId}/events`. Subscribe to the canonical URI for advisory `resources/updated` hints, then read and paginate with `after`, `limit`, and `streamId`. Progress is coarse and redacted: `agentTranscript` rows are assistant/tool upserts partitioned by `(scope, callIndex, executionStartSeq)` and reduced by greatest revision per entry index. The durable cursor is authoritative when hints coalesce or a subscriber falls behind.\n\nEmbedding hosts can drive the same contract with `runDynamicWorkflow` / `WorkflowManager` from `@automatalabs/workflows`; the script contract is identical either way.\n'
|
|
32491
32571
|
},
|
|
32492
32572
|
{
|
|
32493
32573
|
"id": "workflow/models-and-config",
|
|
@@ -32500,9 +32580,9 @@ var AUTHORING_DOC_TOPICS = [
|
|
|
32500
32580
|
"workflow/environment-and-tools",
|
|
32501
32581
|
"workflow/run-lifecycle"
|
|
32502
32582
|
],
|
|
32503
|
-
"bytes":
|
|
32504
|
-
"sha256": "
|
|
32505
|
-
"text": '## Choosing the agent for each call\n\n**Context:** JavaScript passed to the MCP `workflow` tool. Workflow scripts use `agent(prompt, options?)`; REPL evals use a different API.\n\nThe backend is selected **per `agent()` call** from its effective `model` string. One script can plan on one vendor\'s agent, implement on another\'s, and review on a third\'s, handing structured results between them.\n\nThe built-in names (`claude`, `codex`, `opencode`, `pi`) come from the runtime backend registry. Registered custom names extend that set.\n\n- **Omit `model` entirely** for maximum portability. In the MCP server, an explicitly present `AGENTPRISM_DEFAULT_BACKEND` wins; when it is truly unset, the first model-less run for a project performs zero-token backend readiness probes, pins one effective backend before validation/execution, and reuses that pin for the run and resume. The SDK runner itself retains its configured default (`AGENTPRISM_DEFAULT_BACKEND`, historical fallback Claude). A script with no model specs remains backend-portable.\n- **Route by one registered first segment.** Split on the first `/`; ASCII-case-insensitive `claude`, `codex`, `opencode`, `pi`, or a registered custom backend name selects that harness and is stripped exactly once. A custom registration wins on a built-in-name collision.\n- **Use a backend name alone** (`claude`, `codex`, `opencode`, `pi`, or a custom name) to preserve the harness\'s configured default model. No model config call is made.\n- **Everything else goes intact to the default backend.** `anthropic/\u2026`, `openai/\u2026`, bare `opus`, and bare `gpt-\u2026` are not routing aliases. When an id remains after routing, it is sent byte-for-byte: no catalog matching, case folding, bracket parsing, effort/Fast option driving, retry, or fallback. Harness rejection is an agent error.\n- **`tier`** (`"small" | "medium" | "big"`) is a coarse alternative resolved from the host\'s tier config \u2014 use it for "a cheap model" without naming a vendor.\n\nThe published examples use ids verified against live harness catalogs: `claude/opus[1m]`, `codex/gpt-5.6-sol`, and `opencode/zai/glm-5.2`. For Pi, `pi/openrouter/vendor/model-id` strips only `pi/`; Pi then splits provider `openrouter` from model id `vendor/model-id`. Prefer backend-only forms when the desired model is configured inside the harness.\n\nNever guess model ids, mode ids, effort values, or option names from memory. With MCP, call the `workflow` tool using `action:"config"` and optional `harnesses` / `modelFilter`; it returns the live catalog without starting a workflow.\n\nOne no-prompt session per harness, zero tokens: each successful harness entry contains `modes`
|
|
32583
|
+
"bytes": 9653,
|
|
32584
|
+
"sha256": "2c5279f1c2968e4f9fd24393b7c1107e48dbf773ec7462e4502896a3202a3403",
|
|
32585
|
+
"text": '## Choosing the agent for each call\n\n**Context:** JavaScript passed to the MCP `workflow` tool. Workflow scripts use `agent(prompt, options?)`; REPL evals use a different API.\n\nThe backend is selected **per `agent()` call** from its effective `model` string. One script can plan on one vendor\'s agent, implement on another\'s, and review on a third\'s, handing structured results between them.\n\nThe built-in names (`claude`, `codex`, `opencode`, `pi`) come from the runtime backend registry. Registered custom names extend that set.\n\n- **Omit `model` entirely** for maximum portability. In the MCP server, an explicitly present `AGENTPRISM_DEFAULT_BACKEND` wins; when it is truly unset, the first model-less run for a project performs zero-token backend readiness probes, pins one effective backend before validation/execution, and reuses that pin for the run and resume. The SDK runner itself retains its configured default (`AGENTPRISM_DEFAULT_BACKEND`, historical fallback Claude). A script with no model specs remains backend-portable.\n- **Route by one registered first segment.** Split on the first `/`; ASCII-case-insensitive `claude`, `codex`, `opencode`, `pi`, or a registered custom backend name selects that harness and is stripped exactly once. A custom registration wins on a built-in-name collision.\n- **Use a backend name alone** (`claude`, `codex`, `opencode`, `pi`, or a custom name) to preserve the harness\'s configured default model. No model config call is made.\n- **Everything else goes intact to the default backend.** `anthropic/\u2026`, `openai/\u2026`, bare `opus`, and bare `gpt-\u2026` are not routing aliases. When an id remains after routing, it is sent byte-for-byte: no catalog matching, case folding, bracket parsing, effort/Fast option driving, retry, or fallback. Harness rejection is an agent error.\n- **`tier`** (`"small" | "medium" | "big"`) is a coarse alternative resolved from the host\'s tier config \u2014 use it for "a cheap model" without naming a vendor.\n\nThe published examples use ids verified against live harness catalogs: `claude/opus[1m]`, `codex/gpt-5.6-sol`, and `opencode/zai/glm-5.2`. For Pi, `pi/openrouter/vendor/model-id` strips only `pi/`; Pi then splits provider `openrouter` from model id `vendor/model-id`. Prefer backend-only forms when the desired model is configured inside the harness.\n\nNever guess model ids, mode ids, effort values, or option names from memory. With MCP, call the `workflow` tool using `action:"config"` and optional `harnesses` / `modelFilter`; it returns the live catalog without starting a workflow.\n\nOne no-prompt session per harness, zero tokens: each successful harness entry contains `modes`, `defaultModeId`, and its config-option catalog. A non-null `modes` object carries `currentModeId` plus every available mode\'s raw id, name, description, and `_meta`; only exact advertised ids are valid. When omitted, AgentPrism applies Claude `auto`, Codex `agent`, OpenCode `build`, or no Pi mode. `modes:null` means the backend supports no mode. Config options list model ids (including bracket variants like `opus[1m]`), effort levels, and every other negotiable option exactly as the installed harness advertises them. `probed:true` means session/config discovery succeeded, **not** that every backend has proven it can authenticate a first prompt: ACP has no universal zero-token auth-status method, and some agents defer that check. Automatic MCP default selection treats failed probes and explicitly empty built-in model catalogs as unavailable, prefers stronger session-open evidence (Codex authorization; Pi\'s credential-filtered catalog), then falls back to the first session-ready backend whose prompt readiness is unknown. One additional caveat: the bare `config` probe reads each harness with its **default model** selected, and option domains are **model-specific**. An option can appear only after a particular model is selected. Ceilings differ per model. Provider-served variants of the same model can advertise different domains. The authoritative per-model probe is the validator run on your real script: it selects each authored model spec first and echoes that pair\'s advertised modes and options. Confirm every pinned value against its own echoed entry; do not read package internals to discover options.\n\n```js\nconst plan = await agent(PLAN_PROMPT, { label: "plan", model: "opencode/zai/glm-5.2", schema: PLAN });\nconst impl = await agent(implPrompt(plan), { label: "implement", model: "codex/gpt-5.6-sol" });\nconst review = await agent(reviewPrompt(impl), { label: "review", model: "claude/opus[1m]", schema: REVIEW });\n```\n\nUse `configOptions` only for exact ACP session options advertised by that routed harness. With MCP, read the selected harness\'s `action:"config"` result before choosing ids or select values; catalogs vary by harness version, login, and machine.\n\n```js\nconst impl = await agent(implPrompt(plan), {\n label: "implement",\n model: "codex",\n configOptions: { "fast-mode": true, reasoning_effort: "high" },\n});\n```\n\nIds and string/boolean values pass through verbatim in ascending id order, after model selection and before the prompt. There are no aliases, coercion, client-side vocabulary, defaults, or cached catalogs. Copy option ids character-for-character from the catalog, punctuation included \u2014 `"fast-mode"`, not `fast_mode` \u2014 and quote ids that are not valid identifiers. Never put `"model"` in `configOptions`; use the dedicated `model` field. A harness rejection follows the ordinary agent-error path.\n\nPi\'s thought-level option is named `thinkingLevel`, and its choices depend on the exact model in the same call:\n\n```js\nconst review = await agent(REVIEW_PROMPT, {\n label: "pi-review",\n model: "pi/openrouter/vendor/model-id",\n configOptions: { thinkingLevel: "high" },\n});\n```\n\nValidation selects `openrouter/vendor/model-id` before reading Pi\'s choices. A listed value passes unchanged. A recognized value above an ordered model\'s ceiling, or in a model-specific gap, passes with a warning that names the effective clamp target. Pi advertises its SDK-derived domain directly. Claude and Codex are also ordered: when their options omit domain metadata, validation enumerates the advertised models and merges their per-model effort orders. A Claude model without an `effort` option does not support effort, and `default` never becomes a ceiling target. OpenCode and custom backends have no declared value order, so validation is exact-set. An unrecognized or unadvertised value fails with exit code `2`. Enumeration stops at 32 advertised models; a larger or inconsistently ordered catalog warns and falls back to exact advertised-value validation.\n\n**The harness is authoritative.** The client never substitutes a nearby model or silently falls back. A rejected id follows the existing agent-error path; a harness that accepts or ignores it determines the outcome. The public `fallbacks`/`onModelFallback` fields remain for compatibility but model resolution does not emit them.\n\n## Structured output\n\nPass `schema` \u2014 a **plain JSON Schema object literal** (no schema builders exist inside the realm) \u2014 and the call resolves to a **validated object** instead of text:\n\n```js\nconst FINDINGS = {\n type: "object",\n additionalProperties: false,\n required: ["findings"],\n properties: {\n findings: {\n type: "array",\n items: {\n type: "object",\n additionalProperties: false,\n required: ["file", "line", "summary"],\n properties: {\n file: { type: "string", description: "Repo-relative path \u2014 copy it exactly, never invent one" },\n line: { type: "number", description: "1-indexed line the finding anchors to" },\n summary: { type: "string", description: "One sentence stating the defect, grounded in code you actually read" },\n },\n },\n },\n },\n};\n\nconst report = await agent("Review the diff on this branch for correctness bugs.", {\n label: "review", schema: FINDINGS,\n});\nreport.findings.forEach((f) => log(`${f.file}:${f.line} ${f.summary}`));\n```\n\nThe same schema works on **every** backend; only the fulfillment channel differs, and the runner picks it for you: Claude uses its `outputFormat`, Codex its strict `outputSchema`, while Pi, OpenCode, and eligible custom ACP agents receive a client-hosted `StructuredOutput` MCP tool when they advertise HTTP MCP support. Pi accepts stdio, Streamable HTTP, and SSE MCP servers. If no valid tool capture exists, Pi retains the runner\'s common prompt-embedded schema and validated final-text JSON fallback. In every channel the runner validates the value client-side (with type coercion) and re-prompts a bounded number of times before failing the call with non-recoverable `SCHEMA_NONCOMPLIANCE`.\n\nSchema authoring rules that keep all channels healthy:\n\n- Root must be an object; set `additionalProperties: false` and list every property in `required`.\n- Put a `description` on every field \u2014 descriptions are the per-field prompt.\n- Keep schemas structurally simple. Exotic keywords (`oneOf`, `patternProperties`, unusual `format`s, backreference regexes) are normalized or stripped on the wire for some backends \u2014 validation still enforces them client-side, which shows up as re-prompt churn. Prefer `anyOf`, `enum`, and plain types.\n- Keep free-text fields small (tens of lines). An oversized structured output can exhaust schema repair and fail the call.\n- Validation checks structure, not truth. Check load-bearing values in script code (for example, reject findings whose `file` is not in a known file list) before spending more agents on them.\n'
|
|
32506
32586
|
},
|
|
32507
32587
|
{
|
|
32508
32588
|
"id": "workflow/composition-and-failure",
|
|
@@ -32545,9 +32625,9 @@ var AUTHORING_DOC_TOPICS = [
|
|
|
32545
32625
|
"workflow/api-resume-and-backends",
|
|
32546
32626
|
"workflow/models-and-config"
|
|
32547
32627
|
],
|
|
32548
|
-
"bytes":
|
|
32549
|
-
"sha256": "
|
|
32550
|
-
"text": '## Working directory, isolation, confinement\n\n**Context:** JavaScript passed to the MCP `workflow` tool. Workflow scripts use `agent(prompt, options?)`; REPL evals use a different API.\n\n- Every agent session runs in the run\'s base `cwd` unless the call narrows it: `agent({ cwd: "packages/api" })` (relative resolves against the base).\n- `isolation: "worktree"` runs the agent in a **throwaway git worktree** (`<repoRoot>/.agentprism/worktrees/\u2026`) so parallel agents can edit without colliding. The worktree and its branch are **always deleted when the call ends \u2014 an isolated agent\'s file edits are discarded**. Have isolated agents *return their work as data* (a unified diff, a file map, a report) and apply it in a later non-isolated step; use worktrees for experiments, builds, and verification, not for persistent edits. Outside a git repo, isolation degrades to the shared tree with a logged notice.\n- `resume: { filesystem: "read-only" }` is a deprecated compatibility annotation. It is not a runner mode and has no effect on replay; completed calls replay by journal correspondence whether they read or write. Use `mode`, tool policy, prompts, and worktrees when you actually need confinement.\n- `mode` requests an agent-advertised ACP session mode
|
|
32628
|
+
"bytes": 5648,
|
|
32629
|
+
"sha256": "562a2372283f5a26c7ed0247ddf7eb972e51b1ede17a4d6b42758b7756256dfa",
|
|
32630
|
+
"text": '## Working directory, isolation, confinement\n\n**Context:** JavaScript passed to the MCP `workflow` tool. Workflow scripts use `agent(prompt, options?)`; REPL evals use a different API.\n\n- Every agent session runs in the run\'s base `cwd` unless the call narrows it: `agent({ cwd: "packages/api" })` (relative resolves against the base).\n- `isolation: "worktree"` runs the agent in a **throwaway git worktree** (`<repoRoot>/.agentprism/worktrees/\u2026`) so parallel agents can edit without colliding. The worktree and its branch are **always deleted when the call ends \u2014 an isolated agent\'s file edits are discarded**. Have isolated agents *return their work as data* (a unified diff, a file map, a report) and apply it in a later non-isolated step; use worktrees for experiments, builds, and verification, not for persistent edits. Outside a git repo, isolation degrades to the shared tree with a logged notice.\n- `resume: { filesystem: "read-only" }` is a deprecated compatibility annotation. It is not a runner mode and has no effect on replay; completed calls replay by journal correspondence whether they read or write. Use `mode`, tool policy, prompts, and worktrees when you actually need confinement.\n- `mode` requests an exact agent-advertised ACP session mode. Config returns raw names, descriptions, and `_meta`; use those backend-owned explanations instead of inferring from an id. When omitted, AgentPrism applies Claude `auto`, Codex `agent`, OpenCode `build`, or no Pi mode. Automatic preflight rejects an authored or built-in default that the selected backend/model does not advertise. Only set `mode` on calls whose `model` you also pin. Use an explicitly advertised read-only/plan mode for reviewers and auditors that must not write.\n- `agentType: "<name>"` binds a reusable subagent definition \u2014 a Markdown file at `<cwd>/.agentprism/agents/<name>.md` (project) or `~/.agentprism/agents/<name>.md` (user; project wins) whose frontmatter sets tool allow/deny lists, a model, and isolation, and whose body is the role prompt. An unknown name logs a warning and degrades to defaults.\n\n## Where a mutating workflow runs\n\nThe run\'s base `cwd` is the USER\'S checkout \u2014 the working copy they launched the host from. Treat it as borrowed: committing onto whatever branch is checked out, switching branches, or resetting it are defects unless the user asked for exactly that. A script that commits should verify its target workspace in a preflight step, or create its own workspace idempotently, and refuse on a mismatch rather than adapt. `isolation: "worktree"` is NOT such a workspace \u2014 it is per-call and throwaway. Note also that a throwaway worktree branches from the run cwd\'s repository: an isolated agent sees another agent\'s commits only when they are reachable there.\n\n## Wiring tools and inputs into a call\n\n- `mcpServers: [{ name, command, args: [], env: [] }]` attaches MCP servers to that agent\'s session \u2014 the portable way to hand any backend a capability (image generation, a browser, a ticket system). The agent sees the server\'s tools natively. Note `env` is a list of `{ name, value }` pairs (ACP shape), not an object map; HTTP/SSE servers use `{ type: "http", name, url, headers: [] }`.\n- `images: [...]` appends base64 image blocks to the prompt (backends without image support receive a bracketed text note instead).\n- `meta` / `promptMeta` pass generic ACP `_meta` through to `session/new` / `session/prompt` \u2014 the escape hatch for driving a custom agent\'s extension surface.\n- `keepSession: true` keeps a successful agent\'s ACP session re-openable after the run: the re-attach record (sessionId, backend, effective pool identity, cwd, reopen capabilities) lands in `WorkflowRunResult.agentSessions`, and the HOST can continue that conversation later via `runner.loadSession()`. Usage/auth pause failures are kept open automatically so managed resume can continue the interrupted occurrence. Scripts themselves never request reattach.\n\n### Custom ACP backends\n\nAny process that speaks ACP over stdio can serve `agent()` calls \u2014 an in-house browser-QA agent, an image generator, a domain-specific executor. Two ways in:\n\n1. **Host-registered** (preferred): the embedder passes `createAcpRunner({ backends: { browser: { command: "/abs/browser-acp" } } })`; the script just routes with `model: "browser"`.\n2. **Script-declared**: the script itself declares the backend in `meta.backends` \u2014 but declarations are **inert until the host approves them** (an elicitation in the MCP server; `allowScriptBackends` in the SDK), because they spawn commands on the host machine. Don\'t rely on them silently working.\n\n```js\nexport const meta = {\n name: "checkout-qa",\n description: "Implement, then QA the checkout flow in a real browser",\n backends: {\n browser: { command: "browser-acp", args: ["--headless"] }, // requires host approval\n },\n};\n\nconst change = await agent("Implement the coupon-code field per the spec in docs/coupon.md.",\n { label: "implement" }); // default backend\nconst verdict = await agent(\n `Open the app, walk through checkout with coupon SAVE20, and verify the discount line. Change summary:\\n${change}`,\n { label: "qa", model: "browser", // the custom agent\n schema: { type: "object", additionalProperties: false, required: ["passed"],\n properties: { passed: { type: "boolean" }, notes: { type: "string" } } } },\n);\nreturn { change, qa: verdict };\n```\n\nStructured output works on custom backends through the same injected-tool/fallback ladder as OpenCode \u2014 no special-casing in the script.\n'
|
|
32551
32631
|
},
|
|
32552
32632
|
{
|
|
32553
32633
|
"id": "workflow/determinism-and-resume",
|
|
@@ -32575,9 +32655,9 @@ var AUTHORING_DOC_TOPICS = [
|
|
|
32575
32655
|
"workflow/environment-and-tools",
|
|
32576
32656
|
"workflow/api-control-flow"
|
|
32577
32657
|
],
|
|
32578
|
-
"bytes":
|
|
32579
|
-
"sha256": "
|
|
32580
|
-
"text": '# Workflow agent API reference\n\n**Context:** JavaScript passed to the MCP `workflow` tool. Workflow scripts use `agent(prompt, options?)`; REPL evals use a different API.\n\n## `agent(prompt, options?)` \u2014 full option table\n\nReturns the agent\'s final assistant text, or the schema-validated object when `schema` is set. Resolves to `null` when a *recoverable* failure survives all retries.\n\n| option | type | meaning |\n|---|---|---|\n| `label` | `string` | Display/telemetry name; also stamped on every live ACP event for this call. Always set it. Not part of the resume hash. |\n| `phase` | `string` | Assign this call to a phase explicitly (needed inside concurrent stages where the global `phase()` state would race). |\n| `schema` | JSON Schema object | Structured output. Plain object literal only \u2014 no schema builders exist in the realm. Part of the resume hash. |\n| `model` | `string` | Model spec: optional registered harness prefix plus a verbatim id, or a backend-only name. See [Model specs & routing](#model-specs--routing). Part of the resume hash. |\n| `tier` | `"small" \\| "medium" \\| "big"` | Coarse tier resolved from host config; beats phase/meta model, loses to explicit `model`. Part of the resume hash. |\n| `mode` | `string` | ACP session mode id advertised by the selected backend/model.
|
|
32658
|
+
"bytes": 8842,
|
|
32659
|
+
"sha256": "aeda144cdea50062a1d2c42d11e3cb26b058777f50c3285318a8ad1a53319eb4",
|
|
32660
|
+
"text": '# Workflow agent API reference\n\n**Context:** JavaScript passed to the MCP `workflow` tool. Workflow scripts use `agent(prompt, options?)`; REPL evals use a different API.\n\n## `agent(prompt, options?)` \u2014 full option table\n\nReturns the agent\'s final assistant text, or the schema-validated object when `schema` is set. Resolves to `null` when a *recoverable* failure survives all retries.\n\n| option | type | meaning |\n|---|---|---|\n| `label` | `string` | Display/telemetry name; also stamped on every live ACP event for this call. Always set it. Not part of the resume hash. |\n| `phase` | `string` | Assign this call to a phase explicitly (needed inside concurrent stages where the global `phase()` state would race). |\n| `schema` | JSON Schema object | Structured output. Plain object literal only \u2014 no schema builders exist in the realm. Part of the resume hash. |\n| `model` | `string` | Model spec: optional registered harness prefix plus a verbatim id, or a backend-only name. See [Model specs & routing](#model-specs--routing). Part of the resume hash. |\n| `tier` | `"small" \\| "medium" \\| "big"` | Coarse tier resolved from host config; beats phase/meta model, loses to explicit `model`. Part of the resume hash. |\n| `mode` | `string` | Exact ACP session mode id advertised by the selected backend/model. Config preserves each raw name, description, and `_meta`. When omitted, AgentPrism applies Claude `auto`, Codex `agent`, OpenCode `build`, or no Pi mode; `defaultModeId` reports that choice. Authored and built-in defaults are validated before prompting. Part of the resume hash only when authored. |\n| `configOptions` | `Record<string, string \\| boolean>` | Exact ACP session option ids and authored values. Applied in ascending id order after model and before the prompt, with no aliases or coercion. `"model"` is reserved for the dedicated `model` field. Part of the resume hash only when non-empty, with sorted keys. With MCP, read the advertised-options table from `workflow` action `config` before choosing values. |\n| `agentType` | `string` | Bind a named subagent definition (tools allow/deny, model, isolation, role prompt). See [agentType definitions](#agenttype-definitions). Part of the resume hash. |\n| `isolation` | `"worktree"` | Run in a throwaway git worktree branched from the run cwd. **Always removed (worktree + branch) when the call ends** \u2014 edits are discarded; return work as data. Degrades to the shared tree outside a git repo (logged). |\n| `resume` | `{ filesystem: "read-only" }` | Deprecated compatibility annotation. It is recorded as legacy diagnostic provenance, is not sent to the runner or hashed, and has no effect on replay. New scripts should omit it. |\n| `cwd` | `string` | Per-session working directory; relative resolves against the run\'s base cwd. Overridden by worktree isolation. Not hashed. |\n| `timeoutMs` | `number \\| null` | Total wall-clock cap for each attempt. A finite value may tighten a finite host `agentTimeoutMs` ceiling but cannot raise or disable it. With no host ceiling, a finite value applies and `null`/omitted is uncapped. |\n| `idleTimeoutMs` | `number \\| null` | No-backend-activity cap for each attempt. It may tighten a finite host `agentIdleTimeoutMs` ceiling but cannot raise or disable it. |\n| `retries` | `number` | Retries after *recoverable* failures (default 0, host-overridable). Exhausted retries \u21D2 the call resolves `null`. |\n| `mcpServers` | `McpServerConfig[]` | MCP servers attached to this session. Stdio shape: `{ name, command, args: [], env: [{ name, value }] }` (`args`/`env` required, `env` is name/value pairs, not a map); `{ type: "http" \\| "sse", name, url, headers: [] }` also accepted. Not hashed. |\n| `images` | `PromptImage[]` | Base64 image blocks appended to the prompt; backends without image support get a bracketed text note. Not hashed. |\n| `meta` | `object` | ACP `_meta` merged into `session/new` \u2014 session-scoped extension passthrough (pairs with custom backends). Not hashed. |\n| `promptMeta` | `object` | ACP `_meta` merged into `session/prompt` \u2014 turn-scoped passthrough. Backend-computed keys win on conflict. Not hashed. |\n| `keepSession` | `boolean` | Skip release-time best-effort `session/close`; the non-secret re-attach record lands in `WorkflowRunResult.agentSessions` for host-side `loadSession()` / `resumeSession()`. Usage/auth pause failures are kept open automatically for managed continuation. Not identity-hashed; included in the input fingerprint. |\n\nThe total-wall clock measures the whole attempt, including backend startup, model/config setup,\ntool work, and streamed output; it is not an idle timer. The separate idle clock is opt-in and\nre-arms on real backend activity (every ACP `session/update`), never synthetic progress heartbeats.\nSize it above the longest expected backend-silent local tool call. Each retry starts fresh clocks.\nExhaustion is recoverable `AGENT_TIMEOUT` or `AGENT_IDLE_TIMEOUT`: the call resolves to `null`,\nreleases its concurrency slot, and asks the ACP session to cancel. A session that keeps running\nafter the cancellation grace is closed where supported and its pooled child is recycled.\n\nEvery new run, including one admitted with `resumeFromRunId`, resolves host limits from that run\'s\nrequest. It does not inherit `agentTimeoutMs`, `agentIdleTimeoutMs`, retries, concurrency, or\nagent-count values from its source, so pass every operational bound the resumed execution should use.\n\n## Model specs & routing\n\nA `model` string is resolved solely from its first segment, then delegated to the harness:\n\n| spec shape | routes to | notes |\n|---|---|---|\n| *(omitted)* | host-pinned/default backend | MCP: explicit `AGENTPRISM_DEFAULT_BACKEND` wins; when truly unset, zero-token readiness discovery pins one project default before validation/execution and preserves it across resume. SDK runner: configured default, historical fallback `claude`. The selected harness keeps its session default model. Most portable. |\n| `claude`, `codex`, `opencode`, `pi`, or `<custom-name>` | that registered harness | Backend-only: no model config call; the harness default remains active. |\n| `claude/<id>`, `codex/<id>`, `opencode/<id>`, `pi/<id>`, or `<custom-name>/<id>` | that registered harness | Match the first segment ASCII-case-insensitively and strip exactly one segment. Custom names take priority on collision. The remaining `<id>` is sent verbatim, including further `/` characters. For Pi, that remainder is its `<provider>/<model-id>` and Pi preserves any further slashes in the model id. |\n| any other string, including `anthropic/\u2026`, `openai/\u2026`, bare `opus`, or bare `gpt-\u2026` | host default backend | The **entire** authored string is sent verbatim; these are not routing aliases. |\n\nSelection is a single `session/set_config_option` with `configId: "model"` and the exact remaining string. There is no catalog matching, case folding, normalization, bracket parsing, nearest-neighbor selection, sibling effort/Fast option driving, retry, or echo verification. Brackets, dots, and provider-style prefixes are ordinary model-id characters.\n\nWhatever the harness returns is the outcome. A rejection follows the existing agent-error path with no resolution-specific code or model fallback event. `onModelFallback` and `WorkflowRunResult.fallbacks` remain public compatibility surfaces; model resolution does not emit entries, while pause recovery emits `kind: "continuation"` reattach/skip notices.\n\n## Structured output channels\n\nOne author API (`schema`), four fulfillment paths \u2014 chosen automatically per backend:\n\n| backend | channel |\n|---|---|\n| Claude | native `outputFormat`, schema normalized to Anthropic\'s structured-outputs subset (e.g. `oneOf` \u2192 `anyOf`; unsupported keywords/formats stripped on the wire) |\n| Codex | native strict `outputSchema` (OpenAI strict subset normalization) |\n| Pi | a client-hosted `StructuredOutput` MCP tool injected when the agent advertises HTTP MCP support; common prompt-embedded schema and validated final-text JSON fallback |\n| OpenCode / custom ACP | a client-hosted **`StructuredOutput` MCP tool** injected into the session when the agent advertises HTTP MCP support (an agent may show it as `structured_output_StructuredOutput`); otherwise prompt-embedded schema + JSON parse of the final message. Custom backends can opt out of tool injection with `structuredOutputTool: false`. |\n\nPi accepts stdio, Streamable HTTP, and SSE MCP servers; ACP-transport MCP hosting remains client-side.\n\nIn every channel the runner coerces + validates client-side and re-prompts a bounded number of times; the final miss fails the call with non-recoverable `SCHEMA_NONCOMPLIANCE`. Constraints stripped from the wire are still enforced client-side \u2014 an exotic schema keyword shows up as re-prompt churn, so keep schemas simple.\n'
|
|
32581
32661
|
},
|
|
32582
32662
|
{
|
|
32583
32663
|
"id": "workflow/api-control-flow",
|
|
@@ -32620,9 +32700,9 @@ var AUTHORING_DOC_TOPICS = [
|
|
|
32620
32700
|
"workflow/composition-and-failure",
|
|
32621
32701
|
"workflow/checkpoints-and-quality"
|
|
32622
32702
|
],
|
|
32623
|
-
"bytes":
|
|
32624
|
-
"sha256": "
|
|
32625
|
-
"text": '## Worked example \u2014 cross-vendor build with every major primitive\n\n**Context:** JavaScript passed to the MCP `workflow` tool. Workflow scripts use `agent(prompt, options?)`; REPL evals use a different API.\n\n```js\nexport const meta = {\n name: "feature-build",\n description: "Plan, gate on approval, implement, cross-vendor review, fix until green",\n phases: [{ title: "Plan" }, { title: "Implement" }, { title: "Review" }],\n};\n\nconst PLAN = { type: "object", additionalProperties: false, required: ["steps", "risks"],\n properties: {\n steps: { type: "array", items: { type: "string", description: "One concrete implementation step" } },\n risks: { type: "array", items: { type: "string" } } } };\nconst VERDICT = { type: "object", additionalProperties: false, required: ["ok"],\n properties: { ok: { type: "boolean" },\n feedback: { type: "string", description: "Required when ok=false: concretely what to change" } } };\n\nphase("Plan");\nconst plan = await agent(\n `Study this repo, then write an implementation plan for: ${args.feature}. Keep steps concrete.`,\n { label: "plan", model: "opencode/zai/glm-5.2", schema: PLAN },\n);\n\nconst approved = await checkpoint(\n `Implement "${args.feature}" with this plan?\\n- ${plan.steps.join("\\n- ")}\\nRisks: ${plan.risks.join("; ")}`,\n { kind: "confirm", default: true },\n);\nif (!approved) return { implemented: false, plan };\n\nphase("Implement");\nconst outcome = await gate(\n (feedback, attempt) => agent(\n `Implement: ${args.feature}\\nPlan:\\n- ${plan.steps.join("\\n- ")}\\n` +\n `Run the project\'s tests before finishing and report results.` +\n (feedback ? `\\n\\nReviewer feedback on attempt ${attempt}:\\n${feedback}\\nAddress every point.` : ""),\n { label: `implement:${attempt + 1}`, model: "codex/gpt-5.6-sol", retries: 1 },\n ),\n async (report) => {\n if (!report) return { ok: false, feedback: "implementation agent produced no result" };\n phase("Review");\n const reviews = (await parallel([ // two reviewers on different vendors\n () => agent(`Review the working-tree diff for correctness. Implementer\'s report:\\n${report}`,\n { label: "review:correctness", model: "claude/opus[1m]", schema: VERDICT }),\n () => agent(`Review the working-tree diff for regressions and missing tests. Report:\\n${report}`,\n { label: "review:coverage", model: "opencode/zai/glm-5.2", schema: VERDICT }),\n ])).filter(Boolean);\n const rejections = reviews.filter((r) => !r.ok);\n return rejections.length\n ? { ok: false, feedback: rejections.map((r) => r.feedback).join("\\n"), reviews }\n : { ok: true, reviews };\n },\n { attempts: 3 },\n);\n\nreturn { implemented: outcome.ok, attempts: outcome.attempts, reviewVerdict: outcome.verdict, plan };\n```\n\n(
|
|
32703
|
+
"bytes": 6133,
|
|
32704
|
+
"sha256": "267c9831a93a8cb4c6f64fa951782803f4a990b3ed8c69ba3ad75e367a60fb8f",
|
|
32705
|
+
"text": '## Worked example \u2014 cross-vendor build with every major primitive\n\n**Context:** JavaScript passed to the MCP `workflow` tool. Workflow scripts use `agent(prompt, options?)`; REPL evals use a different API.\n\n```js\nexport const meta = {\n name: "feature-build",\n description: "Plan, gate on approval, implement, cross-vendor review, fix until green",\n phases: [{ title: "Plan" }, { title: "Implement" }, { title: "Review" }],\n};\n\nconst PLAN = { type: "object", additionalProperties: false, required: ["steps", "risks"],\n properties: {\n steps: { type: "array", items: { type: "string", description: "One concrete implementation step" } },\n risks: { type: "array", items: { type: "string" } } } };\nconst VERDICT = { type: "object", additionalProperties: false, required: ["ok"],\n properties: { ok: { type: "boolean" },\n feedback: { type: "string", description: "Required when ok=false: concretely what to change" } } };\n\nphase("Plan");\nconst plan = await agent(\n `Study this repo, then write an implementation plan for: ${args.feature}. Keep steps concrete.`,\n { label: "plan", model: "opencode/zai/glm-5.2", schema: PLAN },\n);\n\nconst approved = await checkpoint(\n `Implement "${args.feature}" with this plan?\\n- ${plan.steps.join("\\n- ")}\\nRisks: ${plan.risks.join("; ")}`,\n { kind: "confirm", default: true },\n);\nif (!approved) return { implemented: false, plan };\n\nphase("Implement");\nconst outcome = await gate(\n (feedback, attempt) => agent(\n `Implement: ${args.feature}\\nPlan:\\n- ${plan.steps.join("\\n- ")}\\n` +\n `Run the project\'s tests before finishing and report results.` +\n (feedback ? `\\n\\nReviewer feedback on attempt ${attempt}:\\n${feedback}\\nAddress every point.` : ""),\n { label: `implement:${attempt + 1}`, model: "codex/gpt-5.6-sol", retries: 1 },\n ),\n async (report) => {\n if (!report) return { ok: false, feedback: "implementation agent produced no result" };\n phase("Review");\n const reviews = (await parallel([ // two reviewers on different vendors\n () => agent(`Review the working-tree diff for correctness. Implementer\'s report:\\n${report}`,\n { label: "review:correctness", model: "claude/opus[1m]", schema: VERDICT }),\n () => agent(`Review the working-tree diff for regressions and missing tests. Report:\\n${report}`,\n { label: "review:coverage", model: "opencode/zai/glm-5.2", schema: VERDICT }),\n ])).filter(Boolean);\n const rejections = reviews.filter((r) => !r.ok);\n return rejections.length\n ? { ok: false, feedback: rejections.map((r) => r.feedback).join("\\n"), reviews }\n : { ok: true, reviews };\n },\n { attempts: 3 },\n);\n\nreturn { implemented: outcome.ok, attempts: outcome.attempts, reviewVerdict: outcome.verdict, plan };\n```\n\n(An omitted mode uses AgentPrism\'s autonomous built-in default. For a genuinely read-only planner, inspect the backend-owned mode names/descriptions from `action:"config"` and pin the exact advertised read-only/plan id.)\n\n## Worked example \u2014 fully backend-agnostic audit\n\nNo `model` anywhere: this script runs unchanged on whatever backend the host defaults to.\n\n```js\nexport const meta = {\n name: "edge-case-audit",\n description: "Exhaustively hunt edge-case bugs in a target dir, verify each, report gaps",\n phases: [{ title: "Hunt" }, { title: "Verify" }],\n};\n\nconst BUGS = { type: "object", additionalProperties: false, required: ["bugs"],\n properties: { bugs: { type: "array", items: { type: "object", additionalProperties: false,\n required: ["file", "scenario"], properties: {\n file: { type: "string", description: "Repo-relative path you actually opened" },\n scenario: { type: "string", description: "Concrete input/state \u2192 wrong behavior" } } } } } };\n\nphase("Hunt");\nconst seen = []; // what earlier rounds reported, threaded into each new prompt\nconst candidates = await loopUntilDry({\n round: async (i) => {\n const r = await agent(\n `Round ${i + 1}: find edge-case bugs in ${args.target} not already in this list:\\n` +\n JSON.stringify(seen) + `\\nOnly report what you can ground in code you read.`,\n { label: `hunt:${i + 1}`, schema: BUGS },\n );\n const bugs = r ? r.bugs : [];\n seen.push(...bugs);\n return bugs; // loopUntilDry dedups these by `key` across rounds\n },\n key: (b) => `${b.file}:${b.scenario}`,\n consecutiveEmpty: 2,\n maxRounds: 8,\n});\n\nphase("Verify");\nconst confirmed = (await pipeline(\n candidates,\n (bug) => verify(bug, { reviewers: 3, threshold: 0.66, lens: ["correctness", "reproducibility"] }),\n (v, bug) => (v.real ? bug : null),\n)).filter(Boolean);\n\nconst gaps = await completenessCheck(args, confirmed);\nlog(`${confirmed.length}/${candidates.length} confirmed; complete=${gaps.complete}`);\nreturn { confirmed, missing: gaps.missing ?? [] };\n```\n\n## Automatic validation before admission\n\nThe MCP `workflow` tool validates every run automatically before admission: static parse, mocked dry run, then routed no-prompt config checks. Invalid scripts return `status:"rejected"` diagnostics without creating a run ID, reserving a background slot, or spending tokens. When pinning model, mode, or `configOptions`, use `action:"config"` first.\n\nThe mocked pass executes reachable script control flow with schema-conforming fabricated agent results. It can prove that syntax, metadata, helper calls, and reachable branches are structurally executable, but it cannot prove prompt quality, real-world judgment, or convergence through every branch. Keep loops bounded in script code and inspect validation warnings for declared phases that the default fabricated path did not reach.\n\nThe routed config pass probes each distinct backend/model pair without prompting. Unknown option ids, invalid select values, wrong value types, and the reserved `"model"` config key reject the script with direct alternatives. A backend that cannot be probed produces an explicit warning and leaves only that backend\'s option domain unverified.\n\nFor model/config details, read `workflow/models-and-config`. For edited-script replay patterns, read `workflow/determinism-and-resume`.\n'
|
|
32626
32706
|
},
|
|
32627
32707
|
{
|
|
32628
32708
|
"id": "repl/quickstart",
|
|
@@ -32666,9 +32746,9 @@ var AUTHORING_DOC_TOPICS = [
|
|
|
32666
32746
|
"repl/steering-queueing-and-cancellation",
|
|
32667
32747
|
"repl/api-reference"
|
|
32668
32748
|
],
|
|
32669
|
-
"bytes":
|
|
32670
|
-
"sha256": "
|
|
32671
|
-
"text": '# REPL agent calls and persistent handles\n\nREPL delegation uses:\n\n```js\nagent(modelSpec, task, options?) -> PromiseHandle\n```\n\nThis differs from workflow scripts, whose signature is `agent(prompt, options?)`.\n\n## Model routing\n\n`modelSpec` is required. Use a registered backend name alone to preserve its configured default model:\n\n```js\nconst worker = agent("codex", "Investigate the failing parser test");\n```\n\nUse `backend/model-id` only after model discovery:\n\n```js\nconst worker = agent("claude/verified-model-id", "Review the implementation");\n```\n\nThe known built-ins are Claude, Codex, OpenCode, and pi, plus host-registered custom backends. Unknown backend names reject and enumerate known backends. Use the `workflow` tool\'s `action:"config"` with `harnesses`/`modelFilter`, then `modelSpecs`, before pinning model, mode, or config-option values.
|
|
32749
|
+
"bytes": 3565,
|
|
32750
|
+
"sha256": "26f9868ba7d70fac2465cdb8fc0d22726585b61608d852aeca26b12a762dff96",
|
|
32751
|
+
"text": '# REPL agent calls and persistent handles\n\nREPL delegation uses:\n\n```js\nagent(modelSpec, task, options?) -> PromiseHandle\n```\n\nThis differs from workflow scripts, whose signature is `agent(prompt, options?)`.\n\n## Model routing\n\n`modelSpec` is required. Use a registered backend name alone to preserve its configured default model:\n\n```js\nconst worker = agent("codex", "Investigate the failing parser test");\n```\n\nUse `backend/model-id` only after model discovery:\n\n```js\nconst worker = agent("claude/verified-model-id", "Review the implementation");\n```\n\nThe known built-ins are Claude, Codex, OpenCode, and pi, plus host-registered custom backends. Unknown backend names reject and enumerate known backends. Use the `workflow` tool\'s `action:"config"` with `harnesses`/`modelFilter`, then `modelSpecs`, before pinning model, mode, or config-option values. Read the selected entry\'s harness-owned mode names/descriptions before pinning an exact advertised id. Omission uses `defaultModeId` (Claude auto, Codex agent, OpenCode build; none for Pi).\n\n## Exact option vocabulary\n\n```js\nconst worker = agent("codex", "Inspect the parser", {\n schema: {\n type: "object",\n additionalProperties: false,\n required: ["summary"],\n properties: { summary: { type: "string" } },\n },\n cwd: "/absolute/path",\n mode: "advertised-mode-id",\n configOptions: { advertisedOptionId: "advertised-value" },\n});\n```\n\nOptions are exactly:\n\n- `schema`: plain JSON Schema object; the promise resolves to its validated object.\n- `cwd`: absolute worker session working directory.\n- `mode`: exact ACP mode explicitly listed in the selected backend/model\'s discovered `modes.availableModes`.\n- `configOptions`: exact string/boolean ACP option ids and values.\n\nUnknown option keys reject. Options must be JSON-serializable.\n\n## Preserve the handle\n\nThe returned promise is also the live handle:\n\n```js\nconst worker = agent("pi", "Research the issue");\nconst id = worker.id;\nconst answer = await worker;\n```\n\nDo not write this if you intend to reuse the session:\n\n```js\nconst worker = await agent("pi", "Research the issue");\n```\n\nThat variable stores only the answer and loses access to handle methods.\n\nThe founding handle exposes non-enumerable, immutable members:\n\n- `id`: stable call id such as `"c1"`.\n- `queue(prompt, options?)`: create a distinct durable FIFO future turn.\n- `steer(prompt, options?)`: attempt strict control of only the currently active turn.\n- `cancel()`: cancel the session\'s current public turn.\n\nA queued-turn handle exposes its own `id` and `cancel()`.\n\n## Settlement and failures\n\nWithout `schema`, the founding promise resolves to final assistant text. With `schema`, it resolves to the validated object.\n\nA rejected call carries an error with call/backend attribution where available. Errors whose `recoverable` field is not `false` are treated as recoverable by `parallel()` and `pipeline()` and become `null` slots. A non-recoverable error rejects the surrounding combinator/eval.\n\nDirect `await worker` propagates rejection; catch only errors you can handle meaningfully:\n\n```js\nlet answer;\ntry {\n answer = await worker;\n} catch (error) {\n console.error(error);\n answer = null;\n}\n```\n\n## Session continuity\n\nThe founding answer settling does not erase the handle binding. Queue later prompts on the founding handle to continue the same ACP session. Session continuity depends on the backend\'s continuation capability and the workspace\'s durable lane state. Never fabricate a new handle from a saved id; retain the actual promise-handle binding.\n'
|
|
32672
32752
|
},
|
|
32673
32753
|
{
|
|
32674
32754
|
"id": "repl/steering-queueing-and-cancellation",
|
|
@@ -33020,7 +33100,7 @@ function registerReplTool(mcp, options) {
|
|
|
33020
33100
|
mcp.registerTool(
|
|
33021
33101
|
"repl",
|
|
33022
33102
|
{
|
|
33023
|
-
description: 'A persistent QuickJS-in-WASM JavaScript VM you drive interactively to orchestrate subagents \u2014 one VM per projectDir, addressed by the same project model as the workflow tool. Two actions: eval runs code and holds the call open pumping settlements; interrupt cancels one subagent call (by id) or breaks the running eval (no id). Named bindings, pending subagent calls, raised checkpoints, and `_` (the previous eval\'s completion value) PERSIST in the VM between calls \u2014 a later eval sees the same variables and awaits the same promises. Console logging produces output text only and creates no persistent value; nothing lives in the transcript. For deeper syntax and examples, read docs topic repl/quickstart and then one related repl/* topic. Inside code (JavaScript; top-level await is allowed, top-level return is a syntax error; console output is captured) the host bridge provides agent(modelSpec, task, opts?) \u2192 Promise: spawn an ACP subagent on a registry built-in (currently Claude, Codex, OpenCode, and pi) or a registered custom agent. The spec is "backend/model" (a bare "backend" runs its default model); an unknown backend rejects the call immediately, naming the known backends. The opts keys are schema (a structured-output JSON schema, validated per call), cwd, configOptions (backend-specific knobs, validated at admission), and mode. Before setting mode, use workflow action:"config" for that exact modelSpec and
|
|
33103
|
+
description: 'A persistent QuickJS-in-WASM JavaScript VM you drive interactively to orchestrate subagents \u2014 one VM per projectDir, addressed by the same project model as the workflow tool. Two actions: eval runs code and holds the call open pumping settlements; interrupt cancels one subagent call (by id) or breaks the running eval (no id). Named bindings, pending subagent calls, raised checkpoints, and `_` (the previous eval\'s completion value) PERSIST in the VM between calls \u2014 a later eval sees the same variables and awaits the same promises. Console logging produces output text only and creates no persistent value; nothing lives in the transcript. For deeper syntax and examples, read docs topic repl/quickstart and then one related repl/* topic. Inside code (JavaScript; top-level await is allowed, top-level return is a syntax error; console output is captured) the host bridge provides agent(modelSpec, task, opts?) \u2192 Promise: spawn an ACP subagent on a registry built-in (currently Claude, Codex, OpenCode, and pi) or a registered custom agent. The spec is "backend/model" (a bare "backend" runs its default model); an unknown backend rejects the call immediately, naming the known backends. The opts keys are schema (a structured-output JSON schema, validated per call), cwd, configOptions (backend-specific knobs, validated at admission), and mode. Before setting mode, use workflow action:"config" for that exact modelSpec and read the harness-owned mode descriptions. Omission uses defaultModeId (Claude auto, Codex agent, OpenCode build; none for Pi); pin only an exact advertised id. Unknown option keys reject synchronously. agent() returns a persistent promise-handle. Assign the handle before awaiting it: `const a = agent("codex", "inspect the failure"); const first = await a`. a.steer(text) targets only the currently running turn. It never starts or queues another turn and resolves "injected", "idle", or "unsupported"; transport and protocol failures reject. Steering while idle returns "idle" and loses the instruction by design. `const q = a.queue(text)` creates a distinct FIFO turn on the same session. q.id is available immediately, await q returns that turn\'s answer, and q.cancel() or an out-of-band interrupt of q.id cancels that exact turn. Queueing works on every backend that can continue the session; steering requires the ACP server\'s raw steering advertisement. Do not write `const a = await agent(...)` when you intend to reuse the handle, because that stores only the answer. Persistent-workspace example \u2014 first eval: `const a = agent("codex", "Investigate the parser failure")`; a later eval, only while agents() reports a\'s turn as running: `const steering = await a.steer("Focus on the parser state machine")`; after the founding answer settles: `const first = await a; const q1 = a.queue("Implement the fix"); const q2 = a.queue("Run the focused tests"); console.log(q1.id, q2.id, steering); const fixed = await q1; const tested = await q2`. checkpoint(question) parks a promise for a human answer, resolved by checkpoint.answer(id, value) in a later eval. parallel, pipeline, verify, judgePanel, gate, retry, loopUntilDry, and sleep(ms) round out the guest library. Introspection is in-band: workspace() returns { bindings, inFlight, checkpoints, diagnostics }; agents() lists live agents with their call ids and states; reset() tears the workspace down. `_` holds the previous eval\'s completion value. No fs, no net, no timers beyond sleep. Subagents (6 concurrent per workspace) take stable ids c1, c2, \u2026 used by interrupt and reported by agents(). eval { code } runs the code, then HOLDS THE CALL OPEN pumping settlements up to a soft bound (default 60 000 ms; per-call timeoutMs override; hard cap 120 000 ms). If everything the code waits on settles within the bound the result is the finished shape { output, result? } \u2014 output is ONE newline-joined string (console lines, checkpoint lines like "checkpoint c9: <question>", error renderings), result the completion value\'s repr. If the bound elapses first the result is the still-running shape { output, running: [call ids] } and the eval continues server-side \u2014 any later eval drains what settled, and eval with "" (the empty script) is the documented idempotent poll: it re-executes nothing, only reports. State survives MCP-session churn and daemon restarts: every eval and every settlement drain that changed state persists the workspace to the daemon\'s per-project repl store, and the first touch of a stored workspace restores it and reconciles every outstanding call. A stored snapshot that refuses (corrupt, a format upgrade, a wasm-binary mismatch) AUTO-RESETS \u2014 the file is renamed aside, never deleted, and the next eval\'s output leads with a notice naming the file and reason. Reconcile reports and drain errors live in workspace().diagnostics. On last-client disconnect the workspace drains in-flight subagent turns to completion and closes idle children; the next eligible queued turn re-attaches its founding session lazily. Subagent output passes through UNFILTERED \u2014 backend harness noise (e.g. codex\'s "Warning: Skill descriptions were shortened\u2026") is forwarded verbatim, never curated away. Every result carries the machine-readable shape (see the output schema) as structuredContent alongside the human text.',
|
|
33024
33104
|
// STRICT at the wire too: the MCP SDK strips unknown keys from a
|
|
33025
33105
|
// non-strict object schema before the handler runs, so a deleted
|
|
33026
33106
|
// surface like `refs` would be silently discarded instead of
|
|
@@ -33628,6 +33708,7 @@ function projectHarnessOptions(harnesses) {
|
|
|
33628
33708
|
const options = harness.options ?? [];
|
|
33629
33709
|
return boundValue({
|
|
33630
33710
|
backendId: harness.backendId,
|
|
33711
|
+
defaultModeId: harness.defaultModeId,
|
|
33631
33712
|
model: harness.model,
|
|
33632
33713
|
probed: harness.probed,
|
|
33633
33714
|
error: harness.error,
|
|
@@ -34200,6 +34281,275 @@ function requireDurableStoppedRun(manager, runId) {
|
|
|
34200
34281
|
}
|
|
34201
34282
|
}
|
|
34202
34283
|
|
|
34284
|
+
// ../mcp-server/src/workflow-permissions.ts
|
|
34285
|
+
import { EventEmitter } from "node:events";
|
|
34286
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
34287
|
+
import {
|
|
34288
|
+
decidePermission,
|
|
34289
|
+
redactText as redactText2,
|
|
34290
|
+
truncateUtf8 as truncateUtf83
|
|
34291
|
+
} from "@automatalabs/workflows";
|
|
34292
|
+
var RUN_ID2 = /^[a-z0-9]+-[a-z0-9]+$/;
|
|
34293
|
+
var PERMISSION_ID = /^[0-9a-f-]{36}$/i;
|
|
34294
|
+
var MAX_PUBLIC_REQUEST_BYTES = 64 * 1024;
|
|
34295
|
+
var MAX_PUBLIC_SCALAR_BYTES = 512;
|
|
34296
|
+
var MAX_PERMISSION_OPTIONS = 16;
|
|
34297
|
+
var MAX_OPTION_ID_CODE_UNITS = 512;
|
|
34298
|
+
var MAX_OPTION_ID_BYTES = 2048;
|
|
34299
|
+
var MAX_PUBLIC_ARRAY_ITEMS = 16;
|
|
34300
|
+
var MAX_PUBLIC_OBJECT_KEYS = 20;
|
|
34301
|
+
var MAX_PUBLIC_DEPTH = 4;
|
|
34302
|
+
var SENSITIVE_KEY_PARTS = [
|
|
34303
|
+
"password",
|
|
34304
|
+
"passwd",
|
|
34305
|
+
"secret",
|
|
34306
|
+
"token",
|
|
34307
|
+
"apikey",
|
|
34308
|
+
"credential",
|
|
34309
|
+
"authorization",
|
|
34310
|
+
"cookie",
|
|
34311
|
+
"privatekey"
|
|
34312
|
+
];
|
|
34313
|
+
var PERMISSION_OPTION_KINDS = /* @__PURE__ */ new Set([
|
|
34314
|
+
"allow_once",
|
|
34315
|
+
"allow_always",
|
|
34316
|
+
"reject_once",
|
|
34317
|
+
"reject_always"
|
|
34318
|
+
]);
|
|
34319
|
+
function cloneRequest(request) {
|
|
34320
|
+
return structuredClone(request);
|
|
34321
|
+
}
|
|
34322
|
+
function sensitiveKey(key) {
|
|
34323
|
+
const normalized = key.toLowerCase().replace(/[^a-z0-9]/g, "");
|
|
34324
|
+
return SENSITIVE_KEY_PARTS.some((part) => normalized.includes(part));
|
|
34325
|
+
}
|
|
34326
|
+
function sanitizeString(value, state) {
|
|
34327
|
+
const redacted = redactText2(value);
|
|
34328
|
+
const bounded = truncateUtf83(redacted.value, MAX_PUBLIC_SCALAR_BYTES);
|
|
34329
|
+
state.redacted ||= redacted.redacted;
|
|
34330
|
+
state.truncated ||= bounded !== redacted.value;
|
|
34331
|
+
return bounded;
|
|
34332
|
+
}
|
|
34333
|
+
function sanitizeValue(value, state, depth = 0, ancestors = /* @__PURE__ */ new Set()) {
|
|
34334
|
+
if (value === null || typeof value === "boolean" || typeof value === "number") return value;
|
|
34335
|
+
if (typeof value === "string") return sanitizeString(value, state);
|
|
34336
|
+
if (typeof value !== "object") {
|
|
34337
|
+
state.truncated = true;
|
|
34338
|
+
return null;
|
|
34339
|
+
}
|
|
34340
|
+
if (depth >= MAX_PUBLIC_DEPTH || ancestors.has(value)) {
|
|
34341
|
+
state.truncated = true;
|
|
34342
|
+
return depth >= MAX_PUBLIC_DEPTH ? "[max depth]" : "[cycle]";
|
|
34343
|
+
}
|
|
34344
|
+
const nextAncestors = new Set(ancestors);
|
|
34345
|
+
nextAncestors.add(value);
|
|
34346
|
+
if (Array.isArray(value)) {
|
|
34347
|
+
const kept = value.slice(0, MAX_PUBLIC_ARRAY_ITEMS).map(
|
|
34348
|
+
(entry) => sanitizeValue(entry, state, depth + 1, nextAncestors)
|
|
34349
|
+
);
|
|
34350
|
+
if (value.length > MAX_PUBLIC_ARRAY_ITEMS) state.truncated = true;
|
|
34351
|
+
return kept;
|
|
34352
|
+
}
|
|
34353
|
+
const entries = Object.entries(value);
|
|
34354
|
+
const output = {};
|
|
34355
|
+
for (const [key, child] of entries.slice(0, MAX_PUBLIC_OBJECT_KEYS)) {
|
|
34356
|
+
const outwardKey = sanitizeString(key, state);
|
|
34357
|
+
if (Object.hasOwn(output, outwardKey)) {
|
|
34358
|
+
state.truncated = true;
|
|
34359
|
+
continue;
|
|
34360
|
+
}
|
|
34361
|
+
if (sensitiveKey(key)) {
|
|
34362
|
+
output[outwardKey] = "[REDACTED]";
|
|
34363
|
+
state.redacted = true;
|
|
34364
|
+
} else {
|
|
34365
|
+
output[outwardKey] = sanitizeValue(child, state, depth + 1, nextAncestors);
|
|
34366
|
+
}
|
|
34367
|
+
}
|
|
34368
|
+
if (entries.length > MAX_PUBLIC_OBJECT_KEYS) state.truncated = true;
|
|
34369
|
+
return output;
|
|
34370
|
+
}
|
|
34371
|
+
function validMeta(value) {
|
|
34372
|
+
return value === void 0 || value === null || typeof value === "object" && !Array.isArray(value);
|
|
34373
|
+
}
|
|
34374
|
+
function validOption(option) {
|
|
34375
|
+
return typeof option.optionId === "string" && option.optionId.length > 0 && option.optionId.length <= MAX_OPTION_ID_CODE_UNITS && Buffer.byteLength(option.optionId, "utf8") <= MAX_OPTION_ID_BYTES && typeof option.name === "string" && PERMISSION_OPTION_KINDS.has(option.kind) && validMeta(option._meta);
|
|
34376
|
+
}
|
|
34377
|
+
function sanitizeOption(option, state) {
|
|
34378
|
+
return {
|
|
34379
|
+
optionId: option.optionId,
|
|
34380
|
+
name: sanitizeString(option.name, state),
|
|
34381
|
+
kind: option.kind,
|
|
34382
|
+
...option._meta === void 0 ? {} : { _meta: sanitizeValue(option._meta, state) }
|
|
34383
|
+
};
|
|
34384
|
+
}
|
|
34385
|
+
function safeToolCall(toolCall, state) {
|
|
34386
|
+
if (typeof toolCall.toolCallId !== "string" || toolCall.toolCallId.length === 0) return void 0;
|
|
34387
|
+
const sanitized = sanitizeValue(toolCall, state);
|
|
34388
|
+
if (sanitized === null || typeof sanitized !== "object" || Array.isArray(sanitized)) return void 0;
|
|
34389
|
+
return {
|
|
34390
|
+
...sanitized,
|
|
34391
|
+
toolCallId: sanitizeString(toolCall.toolCallId, state)
|
|
34392
|
+
};
|
|
34393
|
+
}
|
|
34394
|
+
function publicRequest(request) {
|
|
34395
|
+
if (!Array.isArray(request.options) || request.options.length === 0 || request.options.length > MAX_PERMISSION_OPTIONS || !request.options.every(validOption) || !validMeta(request._meta)) return void 0;
|
|
34396
|
+
const optionIds = request.options.map((option) => option.optionId);
|
|
34397
|
+
if (new Set(optionIds).size !== optionIds.length) return void 0;
|
|
34398
|
+
const state = { redacted: false, truncated: false };
|
|
34399
|
+
const toolCall = safeToolCall(request.toolCall, state);
|
|
34400
|
+
if (!toolCall) return void 0;
|
|
34401
|
+
const options = request.options.map((option) => sanitizeOption(option, state));
|
|
34402
|
+
const projected = {
|
|
34403
|
+
toolCall,
|
|
34404
|
+
options,
|
|
34405
|
+
...request._meta === void 0 ? {} : { _meta: sanitizeValue(request._meta, state) }
|
|
34406
|
+
};
|
|
34407
|
+
if (Buffer.byteLength(JSON.stringify(projected), "utf8") <= MAX_PUBLIC_REQUEST_BYTES) {
|
|
34408
|
+
return { request: projected, truncated: state.truncated, redacted: state.redacted };
|
|
34409
|
+
}
|
|
34410
|
+
const minimal = {
|
|
34411
|
+
toolCall: {
|
|
34412
|
+
toolCallId: projected.toolCall.toolCallId,
|
|
34413
|
+
...projected.toolCall.title === void 0 ? {} : { title: projected.toolCall.title },
|
|
34414
|
+
...projected.toolCall.name === void 0 ? {} : { name: projected.toolCall.name },
|
|
34415
|
+
...projected.toolCall.kind === void 0 ? {} : { kind: projected.toolCall.kind },
|
|
34416
|
+
...projected.toolCall.status === void 0 ? {} : { status: projected.toolCall.status }
|
|
34417
|
+
},
|
|
34418
|
+
options: projected.options.map(({ optionId, name, kind }) => ({ optionId, name, kind }))
|
|
34419
|
+
};
|
|
34420
|
+
if (Buffer.byteLength(JSON.stringify(minimal), "utf8") > MAX_PUBLIC_REQUEST_BYTES) return void 0;
|
|
34421
|
+
return { request: minimal, truncated: true, redacted: state.redacted };
|
|
34422
|
+
}
|
|
34423
|
+
function validResponse(response) {
|
|
34424
|
+
if ("_meta" in response) return false;
|
|
34425
|
+
if (response.outcome.outcome === "cancelled") return true;
|
|
34426
|
+
return typeof response.outcome.optionId === "string" && response.outcome.optionId.length > 0 && response.outcome.optionId.length <= MAX_OPTION_ID_CODE_UNITS && Buffer.byteLength(response.outcome.optionId, "utf8") <= MAX_OPTION_ID_BYTES;
|
|
34427
|
+
}
|
|
34428
|
+
var WorkflowPermissionBroker = class {
|
|
34429
|
+
byId = /* @__PURE__ */ new Map();
|
|
34430
|
+
idsByRun = /* @__PURE__ */ new Map();
|
|
34431
|
+
changed = new EventEmitter();
|
|
34432
|
+
detachEvents;
|
|
34433
|
+
resolver = (request, context) => {
|
|
34434
|
+
if (context.backendId === "pi" || context.runId === void 0 || !RUN_ID2.test(context.runId) || context.callIndex === void 0 || !Number.isSafeInteger(context.callIndex) || context.callIndex < 0) {
|
|
34435
|
+
return decidePermission(request, {});
|
|
34436
|
+
}
|
|
34437
|
+
return this.park(request, context);
|
|
34438
|
+
};
|
|
34439
|
+
attach(source) {
|
|
34440
|
+
this.detachEvents?.();
|
|
34441
|
+
this.detachEvents = source.on("permission_request", (event) => this.observeFinalOutcome(event));
|
|
34442
|
+
}
|
|
34443
|
+
dispose() {
|
|
34444
|
+
this.detachEvents?.();
|
|
34445
|
+
this.detachEvents = void 0;
|
|
34446
|
+
for (const entry of [...this.byId.values()]) {
|
|
34447
|
+
this.finish(entry, { outcome: { outcome: "cancelled" } });
|
|
34448
|
+
}
|
|
34449
|
+
this.changed.removeAllListeners();
|
|
34450
|
+
}
|
|
34451
|
+
list(runId) {
|
|
34452
|
+
const ids = this.idsByRun.get(runId);
|
|
34453
|
+
if (!ids) return [];
|
|
34454
|
+
return [...ids].map((id) => this.byId.get(id)?.public).filter((entry) => entry !== void 0).sort(
|
|
34455
|
+
(left, right) => left.callIndex - right.callIndex || left.requestedAt.localeCompare(right.requestedAt) || left.permissionId.localeCompare(right.permissionId)
|
|
34456
|
+
).map((entry) => structuredClone(entry));
|
|
34457
|
+
}
|
|
34458
|
+
has(runId, permissionId) {
|
|
34459
|
+
if (permissionId !== void 0) return this.byId.get(permissionId)?.public.runId === runId;
|
|
34460
|
+
return (this.idsByRun.get(runId)?.size ?? 0) > 0;
|
|
34461
|
+
}
|
|
34462
|
+
async waitForPending(runId) {
|
|
34463
|
+
if (this.has(runId)) return;
|
|
34464
|
+
await new Promise((resolve) => {
|
|
34465
|
+
const eventName = `pending:${runId}`;
|
|
34466
|
+
const done = () => {
|
|
34467
|
+
this.changed.off(eventName, done);
|
|
34468
|
+
resolve();
|
|
34469
|
+
};
|
|
34470
|
+
this.changed.on(eventName, done);
|
|
34471
|
+
if (this.has(runId)) done();
|
|
34472
|
+
});
|
|
34473
|
+
}
|
|
34474
|
+
respond(runId, permissionId, response) {
|
|
34475
|
+
if (!RUN_ID2.test(runId) || !PERMISSION_ID.test(permissionId)) {
|
|
34476
|
+
throw new TypeError("Invalid workflow permission identity");
|
|
34477
|
+
}
|
|
34478
|
+
if (!validResponse(response)) throw new TypeError("Invalid workflow permission response");
|
|
34479
|
+
const entry = this.byId.get(permissionId);
|
|
34480
|
+
if (!entry || entry.public.runId !== runId) {
|
|
34481
|
+
throw new TypeError(`Permission request "${permissionId}" is not pending for run "${runId}"`);
|
|
34482
|
+
}
|
|
34483
|
+
if (response.outcome.outcome === "selected") {
|
|
34484
|
+
const selectedOptionId = response.outcome.optionId;
|
|
34485
|
+
if (!entry.request.options.some((option) => option.optionId === selectedOptionId)) {
|
|
34486
|
+
throw new TypeError(
|
|
34487
|
+
`Permission option ${JSON.stringify(selectedOptionId)} was not advertised by request "${permissionId}"`
|
|
34488
|
+
);
|
|
34489
|
+
}
|
|
34490
|
+
}
|
|
34491
|
+
const accepted = structuredClone(response);
|
|
34492
|
+
const acknowledgement = {
|
|
34493
|
+
permissionId,
|
|
34494
|
+
runId,
|
|
34495
|
+
callIndex: entry.public.callIndex,
|
|
34496
|
+
outcome: structuredClone(accepted.outcome),
|
|
34497
|
+
respondedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
34498
|
+
};
|
|
34499
|
+
this.finish(entry, accepted);
|
|
34500
|
+
return acknowledgement;
|
|
34501
|
+
}
|
|
34502
|
+
park(request, context) {
|
|
34503
|
+
const projection = publicRequest(request);
|
|
34504
|
+
if (!projection) return Promise.resolve({ outcome: { outcome: "cancelled" } });
|
|
34505
|
+
const permissionId = randomUUID2();
|
|
34506
|
+
return new Promise((resolve) => {
|
|
34507
|
+
const entry = {
|
|
34508
|
+
request: cloneRequest(request),
|
|
34509
|
+
public: {
|
|
34510
|
+
version: 1,
|
|
34511
|
+
permissionId,
|
|
34512
|
+
runId: context.runId,
|
|
34513
|
+
callIndex: context.callIndex,
|
|
34514
|
+
backendId: context.backendId,
|
|
34515
|
+
...context.label === void 0 ? {} : { label: context.label },
|
|
34516
|
+
requestedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
34517
|
+
request: projection.request,
|
|
34518
|
+
requestTruncated: projection.truncated,
|
|
34519
|
+
requestRedacted: projection.redacted
|
|
34520
|
+
},
|
|
34521
|
+
settle: resolve
|
|
34522
|
+
};
|
|
34523
|
+
this.byId.set(permissionId, entry);
|
|
34524
|
+
const runIds = this.idsByRun.get(context.runId) ?? /* @__PURE__ */ new Set();
|
|
34525
|
+
runIds.add(permissionId);
|
|
34526
|
+
this.idsByRun.set(context.runId, runIds);
|
|
34527
|
+
this.changed.emit(`run:${context.runId}`);
|
|
34528
|
+
this.changed.emit(`pending:${context.runId}`);
|
|
34529
|
+
});
|
|
34530
|
+
}
|
|
34531
|
+
observeFinalOutcome(event) {
|
|
34532
|
+
for (const entry of this.byId.values()) {
|
|
34533
|
+
if (entry.public.backendId === event.backendId && entry.request.sessionId === event.sessionId && entry.request.toolCall.toolCallId === event.request.toolCall.toolCallId) {
|
|
34534
|
+
this.finish(entry, event.outcome);
|
|
34535
|
+
return;
|
|
34536
|
+
}
|
|
34537
|
+
}
|
|
34538
|
+
}
|
|
34539
|
+
finish(entry, response) {
|
|
34540
|
+
this.remove(entry);
|
|
34541
|
+
entry.settle(response);
|
|
34542
|
+
}
|
|
34543
|
+
remove(entry) {
|
|
34544
|
+
const { permissionId, runId } = entry.public;
|
|
34545
|
+
if (!this.byId.delete(permissionId)) return;
|
|
34546
|
+
const ids = this.idsByRun.get(runId);
|
|
34547
|
+
ids?.delete(permissionId);
|
|
34548
|
+
if (ids?.size === 0) this.idsByRun.delete(runId);
|
|
34549
|
+
this.changed.emit(`run:${runId}`);
|
|
34550
|
+
}
|
|
34551
|
+
};
|
|
34552
|
+
|
|
34203
34553
|
// ../mcp-server/src/server.ts
|
|
34204
34554
|
var SERVER_NAME = "agentprism-workflow";
|
|
34205
34555
|
var DEFAULT_REQUEST_STATE_CODEC = createRequestStateCodec({
|
|
@@ -34207,11 +34557,11 @@ var DEFAULT_REQUEST_STATE_CODEC = createRequestStateCodec({
|
|
|
34207
34557
|
bind: (ctx) => ctx.mcpReq.method
|
|
34208
34558
|
});
|
|
34209
34559
|
var require2 = createRequire(import.meta.url);
|
|
34210
|
-
var SERVER_VERSION = true ? "0.
|
|
34560
|
+
var SERVER_VERSION = true ? "0.38.0" : require2("../package.json").version;
|
|
34211
34561
|
var SERVER_INSTRUCTIONS = [
|
|
34212
34562
|
"This server exposes three model-facing tools for authoring and orchestrating multi-agent work. workflow and repl spawn subagents over the same ACP backends \u2014 the registry built-ins Claude, Codex, OpenCode, and pi, plus any registered custom agents \u2014 and key their durable state by an absolute projectDir (required on the shared daemon; defaults to the server's own project in single-project mode). Backend credentials come from each agent's own login (claude, codex, opencode, pi), so there is nothing auth-shaped to configure here.",
|
|
34213
34563
|
'\u2022 docs \u2014 SELECTIVE VERSION-MATCHED REFERENCE. Omit topic or use topic:"index" for the bounded catalog, then read exactly one workflow/* or repl/* topic. It embeds the selected text/markdown resource, runs no code, opens no backend, and needs no projectDir. Use it when the compact tool descriptions do not contain enough syntax or lifecycle detail.',
|
|
34214
|
-
'\u2022 workflow \u2014 DETERMINISTIC BATCH orchestration. Supply a JavaScript workflow script (inline or by absolute scriptPath) that fans out agent() subagents and optional checkpoint() gates; it runs to completion in the foreground, or background:true returns a durable runId for bounded action:"await"/"inspect"/"stop" calls, with journaling, replay, and resumeFromRunId. Reach for it when the orchestration is known up front and you want it repeatable and resumable. action:"config" discovers the live backend/model option catalog without starting a run, and every run is statically checked, mock-executed, and config-probed before admission. Read docs topic workflow/quickstart first when authoring is unfamiliar.',
|
|
34564
|
+
'\u2022 workflow \u2014 DETERMINISTIC BATCH orchestration. Supply a JavaScript workflow script (inline or by absolute scriptPath) that fans out agent() subagents and optional checkpoint() gates; it runs to completion in the foreground, or background:true returns a durable runId for bounded action:"await"/"inspect"/"permissions-response"/"stop" calls, with journaling, replay, and resumeFromRunId. Await/inspect surface exact live ACP permission options when an agent needs external action. Reach for it when the orchestration is known up front and you want it repeatable and resumable. action:"config" discovers the live backend/model option catalog without starting a run, and every run is statically checked, mock-executed, and config-probed before admission. Read docs topic workflow/quickstart first when authoring is unfamiliar.',
|
|
34215
34565
|
'\u2022 repl \u2014 INTERACTIVE STATEFUL orchestration. A persistent per-project JavaScript VM you drive incrementally with action:"eval"; named bindings, pending subagent calls, raised checkpoints, and `_` (the previous eval\'s completion value) persist between calls and survive daemon restarts. Console logging produces output text only and creates no persistent value. Reach for it when you want to inspect intermediate results and decide the next step adaptively, or keep a human in the loop via checkpoint(). Read docs topic repl/quickstart first when the persistent handle API is unfamiliar.',
|
|
34216
34566
|
"Rule of thumb: use workflow when you can script the whole plan ahead of time; use repl when you want a live, stateful session that evolves call by call."
|
|
34217
34567
|
].join("\n\n");
|
|
@@ -34239,6 +34589,30 @@ function isTerminalStatus(status) {
|
|
|
34239
34589
|
function isAlreadyTerminalForStop(status) {
|
|
34240
34590
|
return status === "completed" || status === "failed" || status === "aborted";
|
|
34241
34591
|
}
|
|
34592
|
+
function permissionInteraction(canElicit) {
|
|
34593
|
+
return {
|
|
34594
|
+
permissionRequests: "may-block",
|
|
34595
|
+
collectWith: ["await", "inspect"],
|
|
34596
|
+
respondWith: "permissions-response",
|
|
34597
|
+
elicitation: canElicit ? "available" : "unavailable"
|
|
34598
|
+
};
|
|
34599
|
+
}
|
|
34600
|
+
async function pendingPermissionsForRun(manager, runId, broker, router) {
|
|
34601
|
+
if (manager.getRun(runId)) return broker.list(runId);
|
|
34602
|
+
return router ? await router.listPermissions(manager, runId) : [];
|
|
34603
|
+
}
|
|
34604
|
+
async function respondToPermission(manager, input, broker, router) {
|
|
34605
|
+
if (manager.getRun(input.runId) && broker.has(input.runId, input.permissionId)) {
|
|
34606
|
+
return broker.respond(input.runId, input.permissionId, input.response);
|
|
34607
|
+
}
|
|
34608
|
+
if (!router) {
|
|
34609
|
+
throw new ProtocolError(
|
|
34610
|
+
ProtocolErrorCode.InvalidParams,
|
|
34611
|
+
`Permission request "${input.permissionId}" is not pending in this server process.`
|
|
34612
|
+
);
|
|
34613
|
+
}
|
|
34614
|
+
return await router.respondPermission(manager, input);
|
|
34615
|
+
}
|
|
34242
34616
|
function readCheckpointDefault(options) {
|
|
34243
34617
|
if (options && typeof options === "object" && "default" in options) {
|
|
34244
34618
|
return options.default;
|
|
@@ -34324,6 +34698,55 @@ function createCheckpointElicitation(prompt, options) {
|
|
|
34324
34698
|
}
|
|
34325
34699
|
};
|
|
34326
34700
|
}
|
|
34701
|
+
function createPermissionElicitation(permission) {
|
|
34702
|
+
const tool = permission.request.toolCall;
|
|
34703
|
+
const title = typeof tool.title === "string" && tool.title.trim() !== "" ? tool.title : `${tool.kind ?? "tool"} request`;
|
|
34704
|
+
const optionLines = permission.request.options.map(
|
|
34705
|
+
(option) => `- ${option.optionId}: ${option.name} (${option.kind})`
|
|
34706
|
+
);
|
|
34707
|
+
return {
|
|
34708
|
+
mode: "form",
|
|
34709
|
+
message: `Workflow agent ${permission.label ? JSON.stringify(permission.label) : `call ${permission.callIndex}`} on ${permission.backendId} requests permission for: ${title}
|
|
34710
|
+
|
|
34711
|
+
${optionLines.join("\n")}
|
|
34712
|
+
|
|
34713
|
+
Select one exact advertised option.`,
|
|
34714
|
+
requestedSchema: {
|
|
34715
|
+
type: "object",
|
|
34716
|
+
properties: {
|
|
34717
|
+
optionId: {
|
|
34718
|
+
type: "string",
|
|
34719
|
+
title: "Permission decision",
|
|
34720
|
+
description: "Exact option advertised by the ACP backend.",
|
|
34721
|
+
enum: permission.request.options.map((option) => option.optionId)
|
|
34722
|
+
}
|
|
34723
|
+
},
|
|
34724
|
+
required: ["optionId"]
|
|
34725
|
+
}
|
|
34726
|
+
};
|
|
34727
|
+
}
|
|
34728
|
+
function formatPendingPermissions(permissions) {
|
|
34729
|
+
if (permissions.length === 0) return "";
|
|
34730
|
+
const lines = [
|
|
34731
|
+
`${permissions.length} workflow permission request(s) require a response:`,
|
|
34732
|
+
...permissions.map((permission) => {
|
|
34733
|
+
const title = permission.request.toolCall.title ?? permission.request.toolCall.kind ?? "tool request";
|
|
34734
|
+
const options = permission.request.options.map((option) => option.optionId).join(", ");
|
|
34735
|
+
return `- ${permission.permissionId} call ${permission.callIndex} (${permission.backendId}) ${title}; options: ${options}`;
|
|
34736
|
+
}),
|
|
34737
|
+
`Use action="permissions-response" with runId, permissionId, and an exact selected optionId or cancelled outcome.`
|
|
34738
|
+
];
|
|
34739
|
+
return truncateUtf84(`
|
|
34740
|
+
${lines.join("\n")}`, 8192, "\u2026[permission summary truncated]");
|
|
34741
|
+
}
|
|
34742
|
+
function permissionResponseFromElicitation(permission, response) {
|
|
34743
|
+
if (response.action !== "accept") return { outcome: { outcome: "cancelled" } };
|
|
34744
|
+
const optionId = response.content?.optionId;
|
|
34745
|
+
if (typeof optionId !== "string" || !permission.request.options.some((option) => option.optionId === optionId)) {
|
|
34746
|
+
return { outcome: { outcome: "cancelled" } };
|
|
34747
|
+
}
|
|
34748
|
+
return { outcome: { outcome: "selected", optionId } };
|
|
34749
|
+
}
|
|
34327
34750
|
function acceptedCheckpointReply(content, options, headlessReply) {
|
|
34328
34751
|
const kind = readCheckpointKind(options);
|
|
34329
34752
|
if (kind === "input") {
|
|
@@ -34445,6 +34868,19 @@ function parseWorkflowRequestState(value, inputHash) {
|
|
|
34445
34868
|
pendingKey: state.pendingKey
|
|
34446
34869
|
};
|
|
34447
34870
|
}
|
|
34871
|
+
if (state.flow === "permission") {
|
|
34872
|
+
if (typeof state.runId !== "string" || !/^[a-z0-9]+-[a-z0-9]+$/.test(state.runId) || typeof state.permissionId !== "string" || !/^[0-9a-f-]{36}$/i.test(state.permissionId)) {
|
|
34873
|
+
throw new ProtocolError(ProtocolErrorCode.InvalidParams, "Invalid workflow permission requestState");
|
|
34874
|
+
}
|
|
34875
|
+
return {
|
|
34876
|
+
version: 1,
|
|
34877
|
+
flow: "permission",
|
|
34878
|
+
inputHash,
|
|
34879
|
+
scriptHash: state.scriptHash,
|
|
34880
|
+
runId: state.runId,
|
|
34881
|
+
permissionId: state.permissionId
|
|
34882
|
+
};
|
|
34883
|
+
}
|
|
34448
34884
|
if (state.flow === "checkpoint") {
|
|
34449
34885
|
if (typeof state.runId !== "string" || !Number.isSafeInteger(state.callIndex) || state.callIndex < 0 || typeof state.checkpointHash !== "string" || !/^[0-9a-f]{64}$/.test(state.checkpointHash) || !Array.isArray(state.approvedKeys) || state.approvedKeys.length > 64 || !state.approvedKeys.every((key) => typeof key === "string" && /^[0-9a-f]{64}$/.test(key)) || state.expiresAt !== void 0 && (typeof state.expiresAt !== "number" || !Number.isFinite(state.expiresAt))) {
|
|
34450
34886
|
throw new ProtocolError(ProtocolErrorCode.InvalidParams, "Invalid workflow checkpoint requestState");
|
|
@@ -34617,10 +35053,10 @@ function formatResumeSummary(eligibility, report) {
|
|
|
34617
35053
|
function formatTerminalSummary(run) {
|
|
34618
35054
|
const lines = [`Workflow run ${run.status}.`, `runId: ${run.runId}`];
|
|
34619
35055
|
if (run.reason) {
|
|
34620
|
-
lines.push(`reason: ${
|
|
35056
|
+
lines.push(`reason: ${truncateUtf84(redactText3(run.reason).value, 512)}`);
|
|
34621
35057
|
}
|
|
34622
35058
|
if (run.resetHint) {
|
|
34623
|
-
lines.push(`reset hint: ${
|
|
35059
|
+
lines.push(`reset hint: ${truncateUtf84(redactText3(run.resetHint).value, 512)}`);
|
|
34624
35060
|
}
|
|
34625
35061
|
if (run.logTail) {
|
|
34626
35062
|
lines.push(`recent run log (last ${run.logTail.lines.length} of ${run.logTail.totalLines}):`);
|
|
@@ -34652,7 +35088,7 @@ function formatTerminalSummary(run) {
|
|
|
34652
35088
|
);
|
|
34653
35089
|
}
|
|
34654
35090
|
}
|
|
34655
|
-
return
|
|
35091
|
+
return truncateUtf84(lines.join("\n"), 12288, "\u2026[text truncated]");
|
|
34656
35092
|
}
|
|
34657
35093
|
function formatRunSummary(run) {
|
|
34658
35094
|
return run.status === "completed" ? formatCompletedSummary(run) : formatTerminalSummary(run);
|
|
@@ -34678,15 +35114,15 @@ function inspectionSummaryLines(status, options = {}) {
|
|
|
34678
35114
|
return lines;
|
|
34679
35115
|
}
|
|
34680
35116
|
function formatInspectionSummary(status) {
|
|
34681
|
-
return
|
|
35117
|
+
return truncateUtf84(inspectionSummaryLines(status).join("\n"), 8192, "\u2026[text truncated]");
|
|
34682
35118
|
}
|
|
34683
35119
|
var MAX_INSPECTION_STRUCTURED_BYTES = 24576;
|
|
34684
35120
|
var MAX_INSPECTION_SCALAR_BYTES = 512;
|
|
34685
35121
|
var MAX_INSPECTION_PHASES = 64;
|
|
34686
35122
|
function retainedInspectionText(value) {
|
|
34687
|
-
const redacted =
|
|
35123
|
+
const redacted = redactText3(value);
|
|
34688
35124
|
return {
|
|
34689
|
-
shortened:
|
|
35125
|
+
shortened: truncateUtf84(redacted.value, MAX_INSPECTION_SCALAR_BYTES) !== redacted.value,
|
|
34690
35126
|
redacted: redacted.redacted
|
|
34691
35127
|
};
|
|
34692
35128
|
}
|
|
@@ -34792,7 +35228,7 @@ function formatStopSummary(result) {
|
|
|
34792
35228
|
"Agent-session cancellation may still be winding down; inspect the per-agent states only if backend cleanup appears hung."
|
|
34793
35229
|
);
|
|
34794
35230
|
}
|
|
34795
|
-
return
|
|
35231
|
+
return truncateUtf84(lines.join("\n"), 8192, "\u2026[text truncated]");
|
|
34796
35232
|
}
|
|
34797
35233
|
function formatPendingStopSummary(result) {
|
|
34798
35234
|
const lines = inspectionSummaryLines(result);
|
|
@@ -34803,7 +35239,7 @@ function formatPendingStopSummary(result) {
|
|
|
34803
35239
|
`Stop request ${result.control.operationId} is durably pending; retry stop, inspect, or await to observe settlement.`,
|
|
34804
35240
|
owner === void 0 ? "No live execution owner is currently discoverable; a later lease holder will apply the intent." : `Execution owner: daemon pid ${owner.pid}${owner.version ? ` v${owner.version}` : ""}${owner.lameDuck ? " (draining)" : ""}.`
|
|
34805
35241
|
);
|
|
34806
|
-
return
|
|
35242
|
+
return truncateUtf84(lines.join("\n"), 8192, "\u2026[text truncated]");
|
|
34807
35243
|
}
|
|
34808
35244
|
function formatAgentCancellationSummary(status, cancellation) {
|
|
34809
35245
|
const lines = inspectionSummaryLines(status);
|
|
@@ -34812,7 +35248,7 @@ function formatAgentCancellationSummary(status, cancellation) {
|
|
|
34812
35248
|
0,
|
|
34813
35249
|
`Agent call ${cancellation.callIndex} ("${cancellation.label}") settled with AGENT_CANCELLED; the workflow run remains live.`
|
|
34814
35250
|
);
|
|
34815
|
-
return
|
|
35251
|
+
return truncateUtf84(lines.join("\n"), 8192, "\u2026[text truncated]");
|
|
34816
35252
|
}
|
|
34817
35253
|
function readScriptAtAdmission(scriptPath) {
|
|
34818
35254
|
try {
|
|
@@ -34861,6 +35297,13 @@ async function settleForegroundRun(manager, started) {
|
|
|
34861
35297
|
throw error51;
|
|
34862
35298
|
}
|
|
34863
35299
|
}
|
|
35300
|
+
async function settleForegroundRunOrPermission(manager, started, broker) {
|
|
35301
|
+
if (broker.has(started.runId)) return { kind: "permission" };
|
|
35302
|
+
return await Promise.race([
|
|
35303
|
+
settleForegroundRun(manager, started).then((run) => ({ kind: "terminal", run })),
|
|
35304
|
+
broker.waitForPending(started.runId).then(() => ({ kind: "permission" }))
|
|
35305
|
+
]);
|
|
35306
|
+
}
|
|
34864
35307
|
function normalizeTokenUsage(usage) {
|
|
34865
35308
|
if (!usage) return void 0;
|
|
34866
35309
|
return {
|
|
@@ -34923,15 +35366,18 @@ var EVENT_LOG_POLL_FALLBACK_CODES = /* @__PURE__ */ new Set([
|
|
|
34923
35366
|
]);
|
|
34924
35367
|
var EVENT_LOG_UNKNOWN_RUN_CODES = /* @__PURE__ */ new Set(["RUN_NOT_FOUND", "ORPHANED_LOG"]);
|
|
34925
35368
|
var TERMINAL_RUN_EVENT_TYPES = /* @__PURE__ */ new Set(["complete", "paused", "error", "stopped"]);
|
|
34926
|
-
async function waitForTerminal(manager, runId, waitMs, signal, localPromise, progress) {
|
|
35369
|
+
async function waitForTerminal(manager, runId, waitMs, signal, localPromise, progress, permissionWait, permissionProbe) {
|
|
34927
35370
|
return await new Promise((resolve, reject) => {
|
|
34928
35371
|
let timer;
|
|
34929
35372
|
let poller;
|
|
35373
|
+
let permissionPoller;
|
|
35374
|
+
let permissionProbeActive = false;
|
|
34930
35375
|
let stream;
|
|
34931
35376
|
let done = false;
|
|
34932
35377
|
const cleanup = () => {
|
|
34933
35378
|
if (timer) clearTimeout(timer);
|
|
34934
35379
|
if (poller) clearInterval(poller);
|
|
35380
|
+
if (permissionPoller) clearInterval(permissionPoller);
|
|
34935
35381
|
stream?.close();
|
|
34936
35382
|
signal.removeEventListener("abort", cancelled);
|
|
34937
35383
|
};
|
|
@@ -34984,6 +35430,23 @@ async function waitForTerminal(manager, runId, waitMs, signal, localPromise, pro
|
|
|
34984
35430
|
() => finish("settled")
|
|
34985
35431
|
);
|
|
34986
35432
|
}
|
|
35433
|
+
if (permissionWait) {
|
|
35434
|
+
void permissionWait.then(() => finish("action-required"), () => void 0);
|
|
35435
|
+
}
|
|
35436
|
+
if (permissionProbe) {
|
|
35437
|
+
const probe = async () => {
|
|
35438
|
+
if (done || permissionProbeActive) return;
|
|
35439
|
+
permissionProbeActive = true;
|
|
35440
|
+
try {
|
|
35441
|
+
if (await permissionProbe()) finish("action-required");
|
|
35442
|
+
} catch {
|
|
35443
|
+
} finally {
|
|
35444
|
+
permissionProbeActive = false;
|
|
35445
|
+
}
|
|
35446
|
+
};
|
|
35447
|
+
permissionPoller = setInterval(() => void probe(), 1e3);
|
|
35448
|
+
void probe();
|
|
35449
|
+
}
|
|
34987
35450
|
try {
|
|
34988
35451
|
const persistence = manager.getPersistence();
|
|
34989
35452
|
const snapshot = persistence.load(runId);
|
|
@@ -35060,7 +35523,7 @@ function formatAwaitSummary(result) {
|
|
|
35060
35523
|
}
|
|
35061
35524
|
}
|
|
35062
35525
|
lines.push(...diagnostics);
|
|
35063
|
-
return
|
|
35526
|
+
return truncateUtf84(lines.join("\n"), 8192, "\u2026[text truncated]");
|
|
35064
35527
|
}
|
|
35065
35528
|
function replEvalTimeoutMs() {
|
|
35066
35529
|
const env = process.env.AGENTPRISM_REPL_EVAL_TIMEOUT_MS;
|
|
@@ -35072,6 +35535,7 @@ function replEvalTimeoutMs() {
|
|
|
35072
35535
|
}
|
|
35073
35536
|
function createWorkflowServer(runner, options = {}) {
|
|
35074
35537
|
const requestStateCodec = options.requestStateCodec ?? DEFAULT_REQUEST_STATE_CODEC;
|
|
35538
|
+
const permissionBroker = options.permissionBroker ?? new WorkflowPermissionBroker();
|
|
35075
35539
|
const mcp = new McpServer(
|
|
35076
35540
|
{ name: SERVER_NAME, version: SERVER_VERSION },
|
|
35077
35541
|
{
|
|
@@ -35112,7 +35576,7 @@ function createWorkflowServer(runner, options = {}) {
|
|
|
35112
35576
|
const backendApprovals = /* @__PURE__ */ new Set();
|
|
35113
35577
|
const replPresence = options.replPresence ?? new ReplPresenceLedger(options.replDrainBoundMs ?? REPL_DRAIN_BOUND_MS);
|
|
35114
35578
|
const resolveContext2 = (input) => {
|
|
35115
|
-
if (input.action === "inspect" || input.action === "await" || input.action === "stop") {
|
|
35579
|
+
if (input.action === "inspect" || input.action === "await" || input.action === "stop" || input.action === "permissions-response") {
|
|
35116
35580
|
return projects.storeFor(input.runId) ?? defaultContext;
|
|
35117
35581
|
}
|
|
35118
35582
|
if (input.projectDir !== void 0) {
|
|
@@ -35140,8 +35604,8 @@ function createWorkflowServer(runner, options = {}) {
|
|
|
35140
35604
|
const workflowToolInputSchema = external_exports.object(workflowToolInputShape);
|
|
35141
35605
|
const workflowToolOutputSchema = workflowToolOutputShape;
|
|
35142
35606
|
const workflowToolConfig = {
|
|
35143
|
-
title: "Discover, validate, run, inspect, await, stop, or narrow-cancel
|
|
35144
|
-
description: 'Author and operate JavaScript agent workflows through one project-scoped tool. A script\'s first statement must be `export const meta = { name, description, phases? }`. When present, phases must be an array of objects shaped `{ title: string, detail?: string, model?: string }`, never an array of strings. Inside the deterministic script realm use agent(prompt, options?) for one subagent; parallel([thunks]) for a barrier; pipeline(items, ...stages) for streaming stages; checkpoint(prompt, options?) for a human gate; phase(title) and log(message) for progress; and return the final JSON-serializable value. Top-level await is supported. Imports, require, network APIs, Date.now(), and Math.random() are unavailable. Always label agent calls; schema is a plain JSON Schema object for structured results. The only agent option keys are label, phase, model, tier, mode, configOptions, schema, cwd, timeoutMs, idleTimeoutMs, retries, isolation:"worktree", resume, agentType, mcpServers, images, meta, promptMeta, and keepSession; unknown keys reject before admission. Every parallel entry must be a thunk: parallel([() => agent(...), () => agent(...)]). For deeper syntax, read docs topic workflow/quickstart and then one related workflow/* topic. Minimal script: `export const meta = { name: "review", description: "Review a target", phases: [{ title: "Review" }] }; phase("Review"); const report = await agent("Review " + args.target, { label: "review" }); return { report };`. Omit model for the server default (explicit AGENTPRISM_DEFAULT_BACKEND, else a zero-token auto-selected project pin), or use a backend name alone to preserve that backend\'s configured default. Before choosing a pinned model, mode, or configOptions, call action:"config" with projectDir and optional harnesses/modelFilter; after choosing a model, pass modelSpecs to read its model-specific options.
|
|
35607
|
+
title: "Discover, validate, run, inspect, await, answer permissions, stop, or narrow-cancel a workflow",
|
|
35608
|
+
description: 'Author and operate JavaScript agent workflows through one project-scoped tool. A script\'s first statement must be `export const meta = { name, description, phases? }`. When present, phases must be an array of objects shaped `{ title: string, detail?: string, model?: string }`, never an array of strings. Inside the deterministic script realm use agent(prompt, options?) for one subagent; parallel([thunks]) for a barrier; pipeline(items, ...stages) for streaming stages; checkpoint(prompt, options?) for a human gate; phase(title) and log(message) for progress; and return the final JSON-serializable value. Top-level await is supported. Imports, require, network APIs, Date.now(), and Math.random() are unavailable. Always label agent calls; schema is a plain JSON Schema object for structured results. The only agent option keys are label, phase, model, tier, mode, configOptions, schema, cwd, timeoutMs, idleTimeoutMs, retries, isolation:"worktree", resume, agentType, mcpServers, images, meta, promptMeta, and keepSession; unknown keys reject before admission. Every parallel entry must be a thunk: parallel([() => agent(...), () => agent(...)]). For deeper syntax, read docs topic workflow/quickstart and then one related workflow/* topic. Minimal script: `export const meta = { name: "review", description: "Review a target", phases: [{ title: "Review" }] }; phase("Review"); const report = await agent("Review " + args.target, { label: "review" }); return { report };`. Omit model for the server default (explicit AGENTPRISM_DEFAULT_BACKEND, else a zero-token auto-selected project pin), or use a backend name alone to preserve that backend\'s configured default. Before choosing a pinned model, mode, or configOptions, call action:"config" with projectDir and optional harnesses/modelFilter; after choosing a model, pass modelSpecs to read its model-specific options. Config returns every harness-advertised mode name, description, and metadata plus AgentPrism\'s omitted-mode default: Claude auto, Codex agent, OpenCode build, and no Pi mode. Pin only exact advertised ids. Config opens no-prompt sessions, spends zero tokens, and starts no workflow. action:"run" automatically performs static validation, a mocked dry run, and routed config checks before admission. Invalid scripts return bounded diagnostics with status:"rejected" and create no run ID, reserve no background slot, and spend no tokens. Run, resume, inspect, await, answer a live ACP permission, or stop an admitted workflow through the same tool. The script orchestrates agent() subagents (and optional checkpoint() gates) over registry built-ins\u2014currently Claude, Codex, OpenCode, and pi\u2014ACP backends, plus registered custom agents. Supply exactly one of inline script or absolute scriptPath; path content is read once and snapshotted at admission. ' + (requireProjectDir ? "config and run REQUIRE projectDir (absolute): it is the discovery cwd and selects the project-scoped run store/default execution cwd. " : "run optionally takes projectDir (absolute) to select the project-scoped run store; default is this server's own project. ") + `inspect/await/stop/permissions-response locate the project store from runId and never accept projectDir. Foreground is the default and streams progress; background:true returns a durable runId for bounded action:"await" calls. run and await honor _meta.progressToken with notifications/progress while they block. Pass resumeFromRunId to execute a new run from a prior journal prefix. In hosts that render MCP Apps, every call of this tool shows a live self-updating run-monitor panel and the panel reports phase starts, pauses, and terminal outcomes on its own \u2014 do NOT poll action:"inspect" to check on a run there; prefer a single bounded action:"await". Use action:"inspect" with a runId when you need machine-readable status data: a safe bounded status, log tail, attributed call previews, and pending ACP permissions. Await returns early with action-required when one appears. Elicitation-capable hosts can present the exact backend options; otherwise use action:"permissions-response" with the returned permissionId and an exact advertised optionId or cancelled outcome. Use action:"stop" to durably abort through the run's execution owner; cross-generation control may return a durable pending operationId before final settlement. Add callIndex to cancel only that live agent and keep the run live. forceOwner explicitly authorizes terminating a superseded owner and is forbidden with callIndex. labelGlob remains an output filter. A final whole-run stop makes resume safe immediately; pending control must be retried or observed with inspect/await. Every admitted script is readable at workflow://runs/{runId}/script and results include resource links. Background runs are tracked per project, capped at four active/starting runs, and use headless checkpoint semantics; checkpointReplies continue a checkpoint pause in a new run.`,
|
|
35145
35609
|
inputSchema: workflowToolInputSchema,
|
|
35146
35610
|
outputSchema: workflowToolOutputSchema,
|
|
35147
35611
|
annotations: void 0
|
|
@@ -35158,7 +35622,7 @@ function createWorkflowServer(runner, options = {}) {
|
|
|
35158
35622
|
let parsedInput = parseWorkflowToolInput(args, { requireProjectDir });
|
|
35159
35623
|
const approvedBackendKeys = /* @__PURE__ */ new Set();
|
|
35160
35624
|
let declinedBackendKey;
|
|
35161
|
-
if (requestState !== void 0) {
|
|
35625
|
+
if (requestState !== void 0 && "approvedKeys" in requestState) {
|
|
35162
35626
|
for (const key of requestState.approvedKeys) approvedBackendKeys.add(key);
|
|
35163
35627
|
}
|
|
35164
35628
|
if (requestState?.flow === "backend-approval") {
|
|
@@ -35231,6 +35695,80 @@ function createWorkflowServer(runner, options = {}) {
|
|
|
35231
35695
|
replPresence.touch(context.repl, options.replClientId?.() ?? "unknown");
|
|
35232
35696
|
const manager = context.manager;
|
|
35233
35697
|
const backgroundRuns = context.backgroundRuns;
|
|
35698
|
+
if (requestState?.flow === "permission") {
|
|
35699
|
+
if (parsedInput.action !== "inspect" && parsedInput.action !== "await" || parsedInput.runId !== requestState.runId) {
|
|
35700
|
+
throw new ProtocolError(
|
|
35701
|
+
ProtocolErrorCode.InvalidParams,
|
|
35702
|
+
"Invalid workflow permission retry: the original inspect/await arguments must be replayed unchanged"
|
|
35703
|
+
);
|
|
35704
|
+
}
|
|
35705
|
+
const pending = await pendingPermissionsForRun(
|
|
35706
|
+
manager,
|
|
35707
|
+
requestState.runId,
|
|
35708
|
+
permissionBroker,
|
|
35709
|
+
options.runControl
|
|
35710
|
+
);
|
|
35711
|
+
const permission = pending.find((entry) => entry.permissionId === requestState.permissionId);
|
|
35712
|
+
if (!permission) {
|
|
35713
|
+
throw new ProtocolError(
|
|
35714
|
+
ProtocolErrorCode.InvalidParams,
|
|
35715
|
+
`Permission request "${requestState.permissionId}" is no longer pending for run "${requestState.runId}"`
|
|
35716
|
+
);
|
|
35717
|
+
}
|
|
35718
|
+
const input2 = inputResponse(ctx.mcpReq.inputResponses, "permission");
|
|
35719
|
+
if (input2.kind !== "elicit") {
|
|
35720
|
+
return inputRequired({
|
|
35721
|
+
inputRequests: { permission: inputRequired.elicit(createPermissionElicitation(permission)) },
|
|
35722
|
+
requestState: await requestStateCodec.mint(requestState, ctx)
|
|
35723
|
+
});
|
|
35724
|
+
}
|
|
35725
|
+
const response = permissionResponseFromElicitation(permission, input2);
|
|
35726
|
+
const acknowledgement = await respondToPermission(
|
|
35727
|
+
manager,
|
|
35728
|
+
{ runId: requestState.runId, permissionId: requestState.permissionId, response },
|
|
35729
|
+
permissionBroker,
|
|
35730
|
+
options.runControl
|
|
35731
|
+
);
|
|
35732
|
+
const status = manager.inspectRun(requestState.runId, {
|
|
35733
|
+
lastN: parsedInput.lastN,
|
|
35734
|
+
labelGlob: parsedInput.labelGlob,
|
|
35735
|
+
logLines: parsedInput.logLines
|
|
35736
|
+
});
|
|
35737
|
+
if (!status) {
|
|
35738
|
+
throw new ProtocolError(
|
|
35739
|
+
ProtocolErrorCode.InvalidParams,
|
|
35740
|
+
`No workflow run found for runId "${requestState.runId}" after its permission response.`
|
|
35741
|
+
);
|
|
35742
|
+
}
|
|
35743
|
+
const lineage = scriptResources.lineage(requestState.runId);
|
|
35744
|
+
const remaining = await pendingPermissionsForRun(
|
|
35745
|
+
manager,
|
|
35746
|
+
requestState.runId,
|
|
35747
|
+
permissionBroker,
|
|
35748
|
+
options.runControl
|
|
35749
|
+
);
|
|
35750
|
+
const projected = addInspectionResourceFields(
|
|
35751
|
+
status,
|
|
35752
|
+
{ scriptUri: workflowScriptUri(requestState.runId), lineage, pendingPermissions: remaining },
|
|
35753
|
+
inspectionRetentionMetadata(manager, requestState.runId, status)
|
|
35754
|
+
);
|
|
35755
|
+
return {
|
|
35756
|
+
structuredContent: {
|
|
35757
|
+
...projected,
|
|
35758
|
+
permissionResponse: acknowledgement
|
|
35759
|
+
},
|
|
35760
|
+
content: [
|
|
35761
|
+
{
|
|
35762
|
+
type: "text",
|
|
35763
|
+
text: `Permission ${acknowledgement.permissionId} resolved for workflow run ${requestState.runId}.
|
|
35764
|
+
${formatInspectionSummary(projected)}`,
|
|
35765
|
+
annotations: { audience: ["assistant"] }
|
|
35766
|
+
},
|
|
35767
|
+
...scriptResources.links(lineage)
|
|
35768
|
+
],
|
|
35769
|
+
isError: false
|
|
35770
|
+
};
|
|
35771
|
+
}
|
|
35234
35772
|
if (requestState?.flow === "checkpoint") {
|
|
35235
35773
|
if (parsedInput.action !== void 0 && parsedInput.action !== "run" || parsedInput.background || parsedInput.resumeFromRunId !== void 0 || parsedInput.checkpointReplies !== void 0) {
|
|
35236
35774
|
throw new ProtocolError(
|
|
@@ -35301,7 +35839,102 @@ function createWorkflowServer(runner, options = {}) {
|
|
|
35301
35839
|
}
|
|
35302
35840
|
}
|
|
35303
35841
|
}
|
|
35842
|
+
if (parsedInput.action === "permissions-response") {
|
|
35843
|
+
const acknowledgement = await respondToPermission(
|
|
35844
|
+
manager,
|
|
35845
|
+
{
|
|
35846
|
+
runId: parsedInput.runId,
|
|
35847
|
+
permissionId: parsedInput.permissionId,
|
|
35848
|
+
response: parsedInput.response
|
|
35849
|
+
},
|
|
35850
|
+
permissionBroker,
|
|
35851
|
+
options.runControl
|
|
35852
|
+
);
|
|
35853
|
+
const status = manager.inspectRun(parsedInput.runId, { lastN: 20, logLines: 20 });
|
|
35854
|
+
if (!status) {
|
|
35855
|
+
throw new ProtocolError(
|
|
35856
|
+
ProtocolErrorCode.InvalidParams,
|
|
35857
|
+
`No workflow run found for runId "${parsedInput.runId}" after its permission response.`
|
|
35858
|
+
);
|
|
35859
|
+
}
|
|
35860
|
+
const lineage = scriptResources.lineage(parsedInput.runId);
|
|
35861
|
+
const pendingPermissions = await pendingPermissionsForRun(
|
|
35862
|
+
manager,
|
|
35863
|
+
parsedInput.runId,
|
|
35864
|
+
permissionBroker,
|
|
35865
|
+
options.runControl
|
|
35866
|
+
);
|
|
35867
|
+
const projected = addInspectionResourceFields(
|
|
35868
|
+
status,
|
|
35869
|
+
{ scriptUri: workflowScriptUri(parsedInput.runId), lineage, pendingPermissions },
|
|
35870
|
+
inspectionRetentionMetadata(manager, parsedInput.runId, status)
|
|
35871
|
+
);
|
|
35872
|
+
return {
|
|
35873
|
+
structuredContent: {
|
|
35874
|
+
...projected,
|
|
35875
|
+
permissionResponse: acknowledgement
|
|
35876
|
+
},
|
|
35877
|
+
content: [
|
|
35878
|
+
{
|
|
35879
|
+
type: "text",
|
|
35880
|
+
text: `Permission ${acknowledgement.permissionId} resolved for workflow run ${parsedInput.runId}.
|
|
35881
|
+
` + formatInspectionSummary(projected) + formatPendingPermissions(pendingPermissions),
|
|
35882
|
+
annotations: { audience: ["assistant"] }
|
|
35883
|
+
},
|
|
35884
|
+
...scriptResources.links(lineage)
|
|
35885
|
+
],
|
|
35886
|
+
isError: false
|
|
35887
|
+
};
|
|
35888
|
+
}
|
|
35304
35889
|
if (parsedInput.action === "inspect") {
|
|
35890
|
+
let pendingPermissions = await pendingPermissionsForRun(
|
|
35891
|
+
manager,
|
|
35892
|
+
parsedInput.runId,
|
|
35893
|
+
permissionBroker,
|
|
35894
|
+
options.runControl
|
|
35895
|
+
);
|
|
35896
|
+
let acknowledgement;
|
|
35897
|
+
const canElicitPermission = Boolean(toolCatalog.clientCapabilities(ctx)?.elicitation);
|
|
35898
|
+
if (pendingPermissions.length > 0 && canElicitPermission) {
|
|
35899
|
+
const permission = pendingPermissions[0];
|
|
35900
|
+
if (options.protocolEra === "modern") {
|
|
35901
|
+
const state = {
|
|
35902
|
+
version: 1,
|
|
35903
|
+
flow: "permission",
|
|
35904
|
+
inputHash,
|
|
35905
|
+
scriptHash: workflowScriptHash(parsedInput.runId),
|
|
35906
|
+
runId: parsedInput.runId,
|
|
35907
|
+
permissionId: permission.permissionId
|
|
35908
|
+
};
|
|
35909
|
+
return inputRequired({
|
|
35910
|
+
inputRequests: { permission: inputRequired.elicit(createPermissionElicitation(permission)) },
|
|
35911
|
+
requestState: await requestStateCodec.mint(state, ctx)
|
|
35912
|
+
});
|
|
35913
|
+
}
|
|
35914
|
+
try {
|
|
35915
|
+
await primeCancellableServerRequestId(mcp.server);
|
|
35916
|
+
const elicited = await mcp.server.elicitInput(createPermissionElicitation(permission), {
|
|
35917
|
+
signal: ctx.mcpReq.signal
|
|
35918
|
+
});
|
|
35919
|
+
acknowledgement = await respondToPermission(
|
|
35920
|
+
manager,
|
|
35921
|
+
{
|
|
35922
|
+
runId: parsedInput.runId,
|
|
35923
|
+
permissionId: permission.permissionId,
|
|
35924
|
+
response: permissionResponseFromElicitation(permission, elicited)
|
|
35925
|
+
},
|
|
35926
|
+
permissionBroker,
|
|
35927
|
+
options.runControl
|
|
35928
|
+
);
|
|
35929
|
+
pendingPermissions = await pendingPermissionsForRun(
|
|
35930
|
+
manager,
|
|
35931
|
+
parsedInput.runId,
|
|
35932
|
+
permissionBroker,
|
|
35933
|
+
options.runControl
|
|
35934
|
+
);
|
|
35935
|
+
} catch {
|
|
35936
|
+
}
|
|
35937
|
+
}
|
|
35305
35938
|
const status = manager.inspectRun(parsedInput.runId, {
|
|
35306
35939
|
lastN: parsedInput.lastN,
|
|
35307
35940
|
labelGlob: parsedInput.labelGlob,
|
|
@@ -35323,18 +35956,24 @@ function createWorkflowServer(runner, options = {}) {
|
|
|
35323
35956
|
status,
|
|
35324
35957
|
{
|
|
35325
35958
|
scriptUri: workflowScriptUri(parsedInput.runId),
|
|
35326
|
-
lineage
|
|
35959
|
+
lineage,
|
|
35960
|
+
pendingPermissions,
|
|
35961
|
+
interaction: permissionInteraction(canElicitPermission)
|
|
35327
35962
|
},
|
|
35328
35963
|
inspectionRetentionMetadata(manager, parsedInput.runId, status)
|
|
35329
35964
|
);
|
|
35330
35965
|
return {
|
|
35331
|
-
structuredContent: {
|
|
35966
|
+
structuredContent: {
|
|
35967
|
+
...projected,
|
|
35968
|
+
...acknowledgement === void 0 ? {} : { permissionResponse: acknowledgement }
|
|
35969
|
+
},
|
|
35332
35970
|
content: [
|
|
35333
35971
|
// Status summaries are model input, not user-facing chat content (the run-monitor
|
|
35334
35972
|
// panel is the user's live view) — the audience annotation says so per MCP core.
|
|
35335
35973
|
{
|
|
35336
35974
|
type: "text",
|
|
35337
|
-
text: formatInspectionSummary(projected)
|
|
35975
|
+
text: formatInspectionSummary(projected) + (acknowledgement ? `
|
|
35976
|
+
Permission ${acknowledgement.permissionId} resolved.` : "") + formatPendingPermissions(pendingPermissions),
|
|
35338
35977
|
annotations: { audience: ["assistant"] }
|
|
35339
35978
|
},
|
|
35340
35979
|
...scriptResources.links(lineage)
|
|
@@ -35585,19 +36224,30 @@ function createWorkflowServer(runner, options = {}) {
|
|
|
35585
36224
|
isError: true
|
|
35586
36225
|
};
|
|
35587
36226
|
}
|
|
36227
|
+
let pendingPermissions = manager.getRun(parsedInput.runId) ? permissionBroker.list(parsedInput.runId) : await pendingPermissionsForRun(
|
|
36228
|
+
manager,
|
|
36229
|
+
parsedInput.runId,
|
|
36230
|
+
permissionBroker,
|
|
36231
|
+
options.runControl
|
|
36232
|
+
);
|
|
35588
36233
|
let returnedBecause;
|
|
35589
36234
|
if (isTerminalStatus(status.status)) {
|
|
35590
36235
|
returnedBecause = "terminal";
|
|
36236
|
+
} else if (pendingPermissions.length > 0) {
|
|
36237
|
+
returnedBecause = "action-required";
|
|
35591
36238
|
} else if (parsedInput.waitMs === 0) {
|
|
35592
36239
|
returnedBecause = "immediate";
|
|
35593
36240
|
} else {
|
|
36241
|
+
const local = manager.getRun(parsedInput.runId) !== void 0;
|
|
35594
36242
|
const waited = await waitForTerminal(
|
|
35595
36243
|
manager,
|
|
35596
36244
|
parsedInput.runId,
|
|
35597
36245
|
parsedInput.waitMs ?? 2e4,
|
|
35598
36246
|
ctx.mcpReq.signal,
|
|
35599
36247
|
backgroundRuns.get(parsedInput.runId),
|
|
35600
|
-
createAwaitProgressReporter(ctx)
|
|
36248
|
+
createAwaitProgressReporter(ctx),
|
|
36249
|
+
local ? permissionBroker.waitForPending(parsedInput.runId) : void 0,
|
|
36250
|
+
!local && options.runControl ? async () => (await options.runControl.listPermissions(manager, parsedInput.runId)).length > 0 : void 0
|
|
35601
36251
|
);
|
|
35602
36252
|
if (waited === AWAIT_CANCELLED) {
|
|
35603
36253
|
return {
|
|
@@ -35621,6 +36271,12 @@ function createWorkflowServer(runner, options = {}) {
|
|
|
35621
36271
|
isError: true
|
|
35622
36272
|
};
|
|
35623
36273
|
}
|
|
36274
|
+
pendingPermissions = await pendingPermissionsForRun(
|
|
36275
|
+
manager,
|
|
36276
|
+
parsedInput.runId,
|
|
36277
|
+
permissionBroker,
|
|
36278
|
+
options.runControl
|
|
36279
|
+
);
|
|
35624
36280
|
status = manager.inspectRun(parsedInput.runId, inspectionOptions);
|
|
35625
36281
|
if (!status) {
|
|
35626
36282
|
return {
|
|
@@ -35633,7 +36289,49 @@ function createWorkflowServer(runner, options = {}) {
|
|
|
35633
36289
|
isError: true
|
|
35634
36290
|
};
|
|
35635
36291
|
}
|
|
35636
|
-
returnedBecause = isTerminalStatus(status.status) ? "terminal" : "timeout";
|
|
36292
|
+
returnedBecause = isTerminalStatus(status.status) ? "terminal" : waited === "action-required" || pendingPermissions.length > 0 ? "action-required" : "timeout";
|
|
36293
|
+
}
|
|
36294
|
+
const canElicitPermission = Boolean(toolCatalog.clientCapabilities(ctx)?.elicitation);
|
|
36295
|
+
if (pendingPermissions.length > 0 && canElicitPermission) {
|
|
36296
|
+
const permission = pendingPermissions[0];
|
|
36297
|
+
if (options.protocolEra === "modern") {
|
|
36298
|
+
const state = {
|
|
36299
|
+
version: 1,
|
|
36300
|
+
flow: "permission",
|
|
36301
|
+
inputHash,
|
|
36302
|
+
scriptHash: workflowScriptHash(parsedInput.runId),
|
|
36303
|
+
runId: parsedInput.runId,
|
|
36304
|
+
permissionId: permission.permissionId
|
|
36305
|
+
};
|
|
36306
|
+
return inputRequired({
|
|
36307
|
+
inputRequests: { permission: inputRequired.elicit(createPermissionElicitation(permission)) },
|
|
36308
|
+
requestState: await requestStateCodec.mint(state, ctx)
|
|
36309
|
+
});
|
|
36310
|
+
}
|
|
36311
|
+
try {
|
|
36312
|
+
await primeCancellableServerRequestId(mcp.server);
|
|
36313
|
+
const elicited = await mcp.server.elicitInput(createPermissionElicitation(permission), {
|
|
36314
|
+
signal: ctx.mcpReq.signal
|
|
36315
|
+
});
|
|
36316
|
+
await respondToPermission(
|
|
36317
|
+
manager,
|
|
36318
|
+
{
|
|
36319
|
+
runId: parsedInput.runId,
|
|
36320
|
+
permissionId: permission.permissionId,
|
|
36321
|
+
response: permissionResponseFromElicitation(permission, elicited)
|
|
36322
|
+
},
|
|
36323
|
+
permissionBroker,
|
|
36324
|
+
options.runControl
|
|
36325
|
+
);
|
|
36326
|
+
pendingPermissions = await pendingPermissionsForRun(
|
|
36327
|
+
manager,
|
|
36328
|
+
parsedInput.runId,
|
|
36329
|
+
permissionBroker,
|
|
36330
|
+
options.runControl
|
|
36331
|
+
);
|
|
36332
|
+
returnedBecause = "permission-resolved";
|
|
36333
|
+
} catch {
|
|
36334
|
+
}
|
|
35637
36335
|
}
|
|
35638
36336
|
const tokenUsage = currentTokenUsage(manager, parsedInput.runId);
|
|
35639
36337
|
const baseOutcome = isTerminalStatus(status.status) ? terminalOutcome(manager, parsedInput.runId, status) : void 0;
|
|
@@ -35649,6 +36347,8 @@ function createWorkflowServer(runner, options = {}) {
|
|
|
35649
36347
|
{
|
|
35650
36348
|
wait,
|
|
35651
36349
|
...tokenUsage === void 0 ? {} : { tokenUsage },
|
|
36350
|
+
pendingPermissions,
|
|
36351
|
+
interaction: permissionInteraction(canElicitPermission),
|
|
35652
36352
|
scriptUri: workflowScriptUri(parsedInput.runId),
|
|
35653
36353
|
lineage
|
|
35654
36354
|
},
|
|
@@ -35664,7 +36364,7 @@ function createWorkflowServer(runner, options = {}) {
|
|
|
35664
36364
|
// Same audience hint as inspect: the await summary is for the model.
|
|
35665
36365
|
{
|
|
35666
36366
|
type: "text",
|
|
35667
|
-
text: formatAwaitSummary(result),
|
|
36367
|
+
text: formatAwaitSummary(result) + formatPendingPermissions(pendingPermissions),
|
|
35668
36368
|
annotations: { audience: ["assistant"] }
|
|
35669
36369
|
},
|
|
35670
36370
|
...scriptResources.links(lineage)
|
|
@@ -35766,7 +36466,7 @@ function createWorkflowServer(runner, options = {}) {
|
|
|
35766
36466
|
} catch (error51) {
|
|
35767
36467
|
if (error51 instanceof NoAutoDefaultBackendError) {
|
|
35768
36468
|
return {
|
|
35769
|
-
content: [{ type: "text", text:
|
|
36469
|
+
content: [{ type: "text", text: truncateUtf84(error51.message, 8192, "\u2026[backend diagnostics truncated]") }],
|
|
35770
36470
|
isError: true
|
|
35771
36471
|
};
|
|
35772
36472
|
}
|
|
@@ -35802,7 +36502,7 @@ function createWorkflowServer(runner, options = {}) {
|
|
|
35802
36502
|
if (admissionWarnings.length > lines.length) {
|
|
35803
36503
|
lines.push(`- \u2026 ${admissionWarnings.length - lines.length} more warning(s) omitted`);
|
|
35804
36504
|
}
|
|
35805
|
-
preflightWarningText =
|
|
36505
|
+
preflightWarningText = truncateUtf84(
|
|
35806
36506
|
`
|
|
35807
36507
|
Preflight warnings (the run was admitted):
|
|
35808
36508
|
${lines.join("\n")}`,
|
|
@@ -35843,15 +36543,15 @@ ${lines.join("\n")}`,
|
|
|
35843
36543
|
let lastActivitySeq = 0;
|
|
35844
36544
|
exec.signal = ctx.mcpReq.signal;
|
|
35845
36545
|
exec.onProgress = (snapshot) => {
|
|
35846
|
-
const
|
|
36546
|
+
const settled2 = snapshot.agents.filter(
|
|
35847
36547
|
(a) => a.status === "done" || a.status === "error" || a.status === "skipped"
|
|
35848
36548
|
).length;
|
|
35849
36549
|
const activity = snapshot.latestActivity;
|
|
35850
36550
|
if (activity && activity.seq > lastActivitySeq) {
|
|
35851
36551
|
lastActivitySeq = activity.seq;
|
|
35852
|
-
reporter(
|
|
36552
|
+
reporter(settled2, snapshot.agents.length || void 0, formatAgentProgressMessage(activity.progress));
|
|
35853
36553
|
} else {
|
|
35854
|
-
reporter(
|
|
36554
|
+
reporter(settled2, snapshot.agents.length || void 0, snapshot.currentPhase);
|
|
35855
36555
|
}
|
|
35856
36556
|
};
|
|
35857
36557
|
const canElicit = Boolean(toolCatalog.clientCapabilities(ctx)?.elicitation);
|
|
@@ -35895,7 +36595,9 @@ ${lines.join("\n")}`,
|
|
|
35895
36595
|
scriptSource,
|
|
35896
36596
|
scriptUri: scriptUri2,
|
|
35897
36597
|
limits: admittedRun.limits,
|
|
35898
|
-
...admittedRun.replayEligibility === void 0 ? {} : { replayEligibility: admittedRun.replayEligibility }
|
|
36598
|
+
...admittedRun.replayEligibility === void 0 ? {} : { replayEligibility: admittedRun.replayEligibility },
|
|
36599
|
+
pendingPermissions: permissionBroker.list(started2.runId),
|
|
36600
|
+
interaction: permissionInteraction(Boolean(toolCatalog.clientCapabilities(ctx)?.elicitation))
|
|
35899
36601
|
},
|
|
35900
36602
|
content: [
|
|
35901
36603
|
{
|
|
@@ -35904,7 +36606,7 @@ ${lines.join("\n")}`,
|
|
|
35904
36606
|
runId: ${started2.runId}
|
|
35905
36607
|
` + (preflightWarningText ? `${preflightWarningText.trimStart()}
|
|
35906
36608
|
` : "") + (admittedRun.replayEligibility ? `${formatResumeSummary(admittedRun.replayEligibility)}
|
|
35907
|
-
` : "") + `Call workflow with action="await" and this runId to wait for its result, or action="inspect" for an immediate status snapshot. If a live run-monitor panel is shown for this run, it self-updates and reports phase starts, pauses, and terminal outcomes \u2014 do not poll inspect for status.`
|
|
36609
|
+
` : "") + `Call workflow with action="await" and this runId to wait for its result, or action="inspect" for an immediate status snapshot. Either action returns early when an ACP permission needs a response; use the elicitation shown by capable clients or action="permissions-response" with an exact advertised option. If a live run-monitor panel is shown for this run, it self-updates and reports phase starts, pauses, and terminal outcomes \u2014 do not poll inspect for status.`
|
|
35908
36610
|
},
|
|
35909
36611
|
...links
|
|
35910
36612
|
],
|
|
@@ -35925,7 +36627,41 @@ runId: ${started2.runId}
|
|
|
35925
36627
|
}
|
|
35926
36628
|
);
|
|
35927
36629
|
executionLatch.admit();
|
|
35928
|
-
const
|
|
36630
|
+
const settled = await settleForegroundRunOrPermission(manager, started, permissionBroker);
|
|
36631
|
+
if (settled.kind === "permission") {
|
|
36632
|
+
const admittedRun = manager.getRun(started.runId);
|
|
36633
|
+
if (!admittedRun?.limits) {
|
|
36634
|
+
throw new ProtocolError(ProtocolErrorCode.InternalError, "Workflow permission wait lost its live run limits");
|
|
36635
|
+
}
|
|
36636
|
+
backgroundRuns.track(started.runId, started.promise);
|
|
36637
|
+
const pendingPermissions = permissionBroker.list(started.runId);
|
|
36638
|
+
const scriptUri2 = workflowScriptUri(started.runId);
|
|
36639
|
+
const canElicitPermission = Boolean(toolCatalog.clientCapabilities(ctx)?.elicitation);
|
|
36640
|
+
return {
|
|
36641
|
+
structuredContent: {
|
|
36642
|
+
runId: started.runId,
|
|
36643
|
+
status: "running",
|
|
36644
|
+
scriptSource,
|
|
36645
|
+
scriptUri: scriptUri2,
|
|
36646
|
+
limits: admittedRun.limits,
|
|
36647
|
+
pendingPermissions,
|
|
36648
|
+
interaction: permissionInteraction(canElicitPermission),
|
|
36649
|
+
...admittedRun.replayEligibility === void 0 ? {} : { replayEligibility: admittedRun.replayEligibility }
|
|
36650
|
+
},
|
|
36651
|
+
content: [
|
|
36652
|
+
{
|
|
36653
|
+
type: "text",
|
|
36654
|
+
text: `Workflow "${admittedRun.snapshot.name}" is still running but requires a permission response.
|
|
36655
|
+
runId: ${started.runId}
|
|
36656
|
+
` + formatPendingPermissions(pendingPermissions).trimStart() + `
|
|
36657
|
+
Call workflow with action="await" or action="inspect"; elicitation-capable clients will present the pending choice, and other clients can use action="permissions-response".`
|
|
36658
|
+
},
|
|
36659
|
+
...scriptResources.links([{ runId: started.runId, uri: scriptUri2, available: true }])
|
|
36660
|
+
],
|
|
36661
|
+
isError: false
|
|
36662
|
+
};
|
|
36663
|
+
}
|
|
36664
|
+
const run = settled.run;
|
|
35929
36665
|
if (options.protocolEra === "modern" && toolCatalog.clientCapabilities(ctx)?.elicitation && run.status === "paused" && run.reason === "checkpoint_required" && run.checkpointContext !== void 0) {
|
|
35930
36666
|
const checkpoint = run.checkpointContext;
|
|
35931
36667
|
const elicitation = createCheckpointElicitation(checkpoint.prompt, checkpoint);
|
|
@@ -36010,7 +36746,7 @@ import { dirname as dirname2 } from "node:path";
|
|
|
36010
36746
|
import { spawn } from "node:child_process";
|
|
36011
36747
|
|
|
36012
36748
|
// ../mcp-server/src/daemon/daemon-info.ts
|
|
36013
|
-
import { randomUUID as
|
|
36749
|
+
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
36014
36750
|
import { createHash as createHash2 } from "node:crypto";
|
|
36015
36751
|
import {
|
|
36016
36752
|
chmodSync as chmodSync2,
|
|
@@ -36083,7 +36819,7 @@ function readDaemonInstance(pid) {
|
|
|
36083
36819
|
}
|
|
36084
36820
|
function writeInfoFile(path, info) {
|
|
36085
36821
|
mkdirSync2(dirname(path), { recursive: true });
|
|
36086
|
-
const tmp = `${path}.${info.pid}.${
|
|
36822
|
+
const tmp = `${path}.${info.pid}.${randomUUID3().slice(0, 8)}.tmp`;
|
|
36087
36823
|
writeFileSync2(tmp, `${JSON.stringify(info, null, 2)}
|
|
36088
36824
|
`, { mode: 384 });
|
|
36089
36825
|
chmodSync2(tmp, 384);
|
|
@@ -36170,7 +36906,7 @@ function compareVersions(a, b) {
|
|
|
36170
36906
|
function claimSpawnLock(fingerprint = envFingerprint()) {
|
|
36171
36907
|
const path = daemonLockPath(fingerprint);
|
|
36172
36908
|
mkdirSync2(dirname(path), { recursive: true });
|
|
36173
|
-
const lock = { pid: process.pid, startedAt: (/* @__PURE__ */ new Date()).toISOString(), token:
|
|
36909
|
+
const lock = { pid: process.pid, startedAt: (/* @__PURE__ */ new Date()).toISOString(), token: randomUUID3() };
|
|
36174
36910
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
36175
36911
|
try {
|
|
36176
36912
|
writeFileSync2(path, JSON.stringify(lock), { flag: "wx", mode: 384 });
|
|
@@ -36320,7 +37056,7 @@ async function ensureDaemonRunning(options) {
|
|
|
36320
37056
|
}
|
|
36321
37057
|
|
|
36322
37058
|
// ../mcp-server/src/daemon/run-daemon.ts
|
|
36323
|
-
import { randomUUID as
|
|
37059
|
+
import { randomUUID as randomUUID6 } from "node:crypto";
|
|
36324
37060
|
import { createAcpRunner } from "@automatalabs/workflows";
|
|
36325
37061
|
|
|
36326
37062
|
// ../mcp-server/src/daemon/daemon-lifecycle.ts
|
|
@@ -36402,7 +37138,7 @@ function installDaemonLifecycle(options) {
|
|
|
36402
37138
|
|
|
36403
37139
|
// ../mcp-server/src/daemon/http-daemon.ts
|
|
36404
37140
|
import http from "node:http";
|
|
36405
|
-
import { randomUUID as
|
|
37141
|
+
import { randomUUID as randomUUID5 } from "node:crypto";
|
|
36406
37142
|
|
|
36407
37143
|
// ../../node_modules/.pnpm/@hono+node-server@1.19.14_hono@4.12.27/node_modules/@hono/node-server/dist/index.mjs
|
|
36408
37144
|
import { Http2ServerRequest as Http2ServerRequest2, constants as h2constants } from "http2";
|
|
@@ -37472,7 +38208,7 @@ function verifyRunControlRequest(key, input) {
|
|
|
37472
38208
|
}
|
|
37473
38209
|
|
|
37474
38210
|
// ../mcp-server/src/daemon/run-control.ts
|
|
37475
|
-
import { randomUUID as
|
|
38211
|
+
import { randomUUID as randomUUID4 } from "node:crypto";
|
|
37476
38212
|
var FORWARD_TIMEOUT_MS = 5e3;
|
|
37477
38213
|
var FORCE_TERM_WAIT_MS = 5e3;
|
|
37478
38214
|
var FORCE_KILL_WAIT_MS = 2e3;
|
|
@@ -37512,12 +38248,14 @@ var DaemonRunControl = class {
|
|
|
37512
38248
|
this.fetchImpl = options.fetch ?? fetch;
|
|
37513
38249
|
this.killProcess = options.kill ?? ((pid, signal) => process.kill(pid, signal));
|
|
37514
38250
|
this.isPidAlive = options.isPidAlive ?? pidIsAlive;
|
|
38251
|
+
this.permissionBroker = options.permissionBroker ?? new WorkflowPermissionBroker();
|
|
37515
38252
|
}
|
|
37516
38253
|
options;
|
|
37517
38254
|
log;
|
|
37518
38255
|
fetchImpl;
|
|
37519
38256
|
killProcess;
|
|
37520
38257
|
isPidAlive;
|
|
38258
|
+
permissionBroker;
|
|
37521
38259
|
processingPending;
|
|
37522
38260
|
async resolveOwner(manager, runId) {
|
|
37523
38261
|
const lease = manager.getPersistence().inspectRunLease?.(runId);
|
|
@@ -37600,6 +38338,24 @@ var DaemonRunControl = class {
|
|
|
37600
38338
|
return { ok: false, code: "NOT_OWNER", message: `Daemon has no live run ${request.runId}` };
|
|
37601
38339
|
}
|
|
37602
38340
|
try {
|
|
38341
|
+
if (request.action === "list-permissions") {
|
|
38342
|
+
return {
|
|
38343
|
+
ok: true,
|
|
38344
|
+
outcome: "permissions-listed",
|
|
38345
|
+
permissions: this.permissionBroker.list(request.runId)
|
|
38346
|
+
};
|
|
38347
|
+
}
|
|
38348
|
+
if (request.action === "respond-permission") {
|
|
38349
|
+
return {
|
|
38350
|
+
ok: true,
|
|
38351
|
+
outcome: "permission-responded",
|
|
38352
|
+
acknowledgement: this.permissionBroker.respond(
|
|
38353
|
+
request.runId,
|
|
38354
|
+
request.permissionId,
|
|
38355
|
+
request.response
|
|
38356
|
+
)
|
|
38357
|
+
};
|
|
38358
|
+
}
|
|
37603
38359
|
const cancellation = await manager.cancelAgentCall(request.runId, request.callIndex);
|
|
37604
38360
|
return { ok: true, outcome: "agent-cancelled", cancellation };
|
|
37605
38361
|
} catch (error51) {
|
|
@@ -37664,6 +38420,71 @@ var DaemonRunControl = class {
|
|
|
37664
38420
|
}
|
|
37665
38421
|
}
|
|
37666
38422
|
}
|
|
38423
|
+
async listPermissions(manager, runId) {
|
|
38424
|
+
if (manager.getRun(runId)) return this.permissionBroker.list(runId);
|
|
38425
|
+
const owner = await this.resolveOwner(manager, runId);
|
|
38426
|
+
if (!owner) return [];
|
|
38427
|
+
if (!this.controlCapable(owner)) {
|
|
38428
|
+
throw new ProtocolError(
|
|
38429
|
+
ProtocolErrorCode.InvalidParams,
|
|
38430
|
+
`${actionableOwnerMessage(runId, owner, "permission inspection")} Pending permissions are live execution state and require a control-capable owner.`
|
|
38431
|
+
);
|
|
38432
|
+
}
|
|
38433
|
+
let response;
|
|
38434
|
+
try {
|
|
38435
|
+
response = await this.post(owner, {
|
|
38436
|
+
operationId: randomUUID4(),
|
|
38437
|
+
runId,
|
|
38438
|
+
action: "list-permissions"
|
|
38439
|
+
});
|
|
38440
|
+
} catch (error51) {
|
|
38441
|
+
throw new ProtocolError(
|
|
38442
|
+
ProtocolErrorCode.InternalError,
|
|
38443
|
+
`${actionableOwnerMessage(runId, owner, "permission inspection")} ${String(error51)}`
|
|
38444
|
+
);
|
|
38445
|
+
}
|
|
38446
|
+
if (!response.ok || response.outcome !== "permissions-listed") {
|
|
38447
|
+
throw new ProtocolError(
|
|
38448
|
+
response.ok || response.code === "INTERNAL_ERROR" ? ProtocolErrorCode.InternalError : ProtocolErrorCode.InvalidParams,
|
|
38449
|
+
response.ok ? "Owner returned an invalid permission-list response." : response.message
|
|
38450
|
+
);
|
|
38451
|
+
}
|
|
38452
|
+
return response.permissions;
|
|
38453
|
+
}
|
|
38454
|
+
async respondPermission(manager, input) {
|
|
38455
|
+
if (manager.getRun(input.runId) && this.permissionBroker.has(input.runId, input.permissionId)) {
|
|
38456
|
+
return this.permissionBroker.respond(input.runId, input.permissionId, input.response);
|
|
38457
|
+
}
|
|
38458
|
+
const owner = await this.resolveOwner(manager, input.runId);
|
|
38459
|
+
if (!owner || !this.controlCapable(owner)) {
|
|
38460
|
+
throw new ProtocolError(
|
|
38461
|
+
ProtocolErrorCode.InvalidParams,
|
|
38462
|
+
`${actionableOwnerMessage(input.runId, owner, "permission response")} A permission response cannot be reconstructed after owner loss.`
|
|
38463
|
+
);
|
|
38464
|
+
}
|
|
38465
|
+
let response;
|
|
38466
|
+
try {
|
|
38467
|
+
response = await this.post(owner, {
|
|
38468
|
+
operationId: randomUUID4(),
|
|
38469
|
+
runId: input.runId,
|
|
38470
|
+
action: "respond-permission",
|
|
38471
|
+
permissionId: input.permissionId,
|
|
38472
|
+
response: input.response
|
|
38473
|
+
});
|
|
38474
|
+
} catch (error51) {
|
|
38475
|
+
throw new ProtocolError(
|
|
38476
|
+
ProtocolErrorCode.InternalError,
|
|
38477
|
+
`${actionableOwnerMessage(input.runId, owner, "permission response")} ${String(error51)}`
|
|
38478
|
+
);
|
|
38479
|
+
}
|
|
38480
|
+
if (!response.ok || response.outcome !== "permission-responded") {
|
|
38481
|
+
throw new ProtocolError(
|
|
38482
|
+
response.ok || response.code === "INTERNAL_ERROR" ? ProtocolErrorCode.InternalError : ProtocolErrorCode.InvalidParams,
|
|
38483
|
+
response.ok ? "Owner returned an invalid permission-response acknowledgement." : response.message
|
|
38484
|
+
);
|
|
38485
|
+
}
|
|
38486
|
+
return response.acknowledgement;
|
|
38487
|
+
}
|
|
37667
38488
|
async control(manager, input) {
|
|
37668
38489
|
let owner = await this.resolveOwner(manager, input.runId);
|
|
37669
38490
|
if (input.callIndex !== void 0) {
|
|
@@ -37676,7 +38497,7 @@ var DaemonRunControl = class {
|
|
|
37676
38497
|
let response;
|
|
37677
38498
|
try {
|
|
37678
38499
|
response = await this.post(owner, {
|
|
37679
|
-
operationId:
|
|
38500
|
+
operationId: randomUUID4(),
|
|
37680
38501
|
runId: input.runId,
|
|
37681
38502
|
action: "cancel-agent",
|
|
37682
38503
|
callIndex: input.callIndex
|
|
@@ -37906,14 +38727,29 @@ function writeControlResponse(res, status, body) {
|
|
|
37906
38727
|
res.writeHead(status, { "Content-Type": "application/json" });
|
|
37907
38728
|
res.end(JSON.stringify(body));
|
|
37908
38729
|
}
|
|
38730
|
+
function isPermissionResponse(value) {
|
|
38731
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
|
|
38732
|
+
const row = value;
|
|
38733
|
+
const keys = Object.keys(row).sort();
|
|
38734
|
+
if (keys.join(",") !== "outcome") return false;
|
|
38735
|
+
const outcome = row.outcome;
|
|
38736
|
+
if (outcome === null || typeof outcome !== "object" || Array.isArray(outcome)) return false;
|
|
38737
|
+
const decision = outcome;
|
|
38738
|
+
const decisionKeys = Object.keys(decision).sort().join(",");
|
|
38739
|
+
if (decision.outcome === "cancelled") return decisionKeys === "outcome";
|
|
38740
|
+
return decision.outcome === "selected" && typeof decision.optionId === "string" && decision.optionId.length > 0 && decisionKeys === "optionId,outcome";
|
|
38741
|
+
}
|
|
37909
38742
|
function isInternalRunControlRequest(value) {
|
|
37910
38743
|
if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
|
|
37911
38744
|
const row = value;
|
|
37912
38745
|
const keys = Object.keys(row).sort();
|
|
37913
38746
|
if (typeof row.operationId !== "string" || !/^[0-9a-f-]{36}$/i.test(row.operationId) || typeof row.runId !== "string" || !/^[a-z0-9]+-[a-z0-9]+$/.test(row.runId)) return false;
|
|
37914
|
-
if (row.action === "stop") {
|
|
38747
|
+
if (row.action === "stop" || row.action === "list-permissions") {
|
|
37915
38748
|
return keys.join(",") === "action,operationId,runId";
|
|
37916
38749
|
}
|
|
38750
|
+
if (row.action === "respond-permission") {
|
|
38751
|
+
return typeof row.permissionId === "string" && /^[0-9a-f-]{36}$/i.test(row.permissionId) && isPermissionResponse(row.response) && keys.join(",") === "action,operationId,permissionId,response,runId";
|
|
38752
|
+
}
|
|
37917
38753
|
return row.action === "cancel-agent" && Number.isSafeInteger(row.callIndex) && row.callIndex >= 0 && keys.join(",") === "action,callIndex,operationId,runId";
|
|
37918
38754
|
}
|
|
37919
38755
|
async function handleRunControlRequest(req, res, key, runControl) {
|
|
@@ -37981,11 +38817,12 @@ async function createDaemon(options) {
|
|
|
37981
38817
|
const log = options.log ?? ((line) => console.error(line));
|
|
37982
38818
|
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
37983
38819
|
const ownPid = options.ownPid ?? process.pid;
|
|
37984
|
-
const ownInstanceId = options.ownInstanceId ??
|
|
38820
|
+
const ownInstanceId = options.ownInstanceId ?? randomUUID5();
|
|
37985
38821
|
const version2 = options.version ?? SERVER_VERSION;
|
|
37986
38822
|
const isSuperseded = options.isSuperseded ?? (() => isSupersededBy(ownPid));
|
|
37987
38823
|
const familyFingerprint = envFingerprint(env);
|
|
37988
38824
|
const sessions = new SessionRegistry();
|
|
38825
|
+
const permissionBroker = options.permissionBroker ?? new WorkflowPermissionBroker();
|
|
37989
38826
|
const projects = new WorkflowProjectRegistry(options.runner, { leaseOwnerId: ownInstanceId });
|
|
37990
38827
|
const runControlKey = loadOrCreateRunControlKey();
|
|
37991
38828
|
const runControl = new DaemonRunControl({
|
|
@@ -37993,6 +38830,7 @@ async function createDaemon(options) {
|
|
|
37993
38830
|
ownPid,
|
|
37994
38831
|
ownInstanceId,
|
|
37995
38832
|
key: runControlKey,
|
|
38833
|
+
permissionBroker,
|
|
37996
38834
|
log
|
|
37997
38835
|
});
|
|
37998
38836
|
const replDrainBoundMs = options.replDrainBoundMs ?? options.sessionTtlMs ?? REPL_DRAIN_BOUND_MS;
|
|
@@ -38015,7 +38853,7 @@ async function createDaemon(options) {
|
|
|
38015
38853
|
};
|
|
38016
38854
|
modernHandler = createMcpHandler(
|
|
38017
38855
|
() => {
|
|
38018
|
-
const clientId = `modern:${
|
|
38856
|
+
const clientId = `modern:${randomUUID5()}`;
|
|
38019
38857
|
return createWorkflowServer(options.runner, {
|
|
38020
38858
|
projects,
|
|
38021
38859
|
requireProjectDir: true,
|
|
@@ -38028,7 +38866,8 @@ async function createDaemon(options) {
|
|
|
38028
38866
|
requestStateCodec,
|
|
38029
38867
|
disconnectReplClientOnClose: true,
|
|
38030
38868
|
modernNotifier,
|
|
38031
|
-
runControl
|
|
38869
|
+
runControl,
|
|
38870
|
+
permissionBroker
|
|
38032
38871
|
});
|
|
38033
38872
|
},
|
|
38034
38873
|
{
|
|
@@ -38084,7 +38923,7 @@ async function createDaemon(options) {
|
|
|
38084
38923
|
return;
|
|
38085
38924
|
}
|
|
38086
38925
|
const transport = new NodeStreamableHTTPServerTransport({
|
|
38087
|
-
sessionIdGenerator: () =>
|
|
38926
|
+
sessionIdGenerator: () => randomUUID5(),
|
|
38088
38927
|
eventStore: new BoundedEventStore(),
|
|
38089
38928
|
onsessioninitialized: (sid) => {
|
|
38090
38929
|
sessions.add({
|
|
@@ -38107,7 +38946,8 @@ async function createDaemon(options) {
|
|
|
38107
38946
|
replClientId: () => transport.sessionId,
|
|
38108
38947
|
replDrainBoundMs,
|
|
38109
38948
|
replEvalBreakChannel: options.evalBreakChannel,
|
|
38110
|
-
runControl
|
|
38949
|
+
runControl,
|
|
38950
|
+
permissionBroker
|
|
38111
38951
|
});
|
|
38112
38952
|
await server.connect(transport);
|
|
38113
38953
|
const protocolOnClose = transport.onclose;
|
|
@@ -38205,6 +39045,7 @@ async function createDaemon(options) {
|
|
|
38205
39045
|
detachModernRunEvent();
|
|
38206
39046
|
detachModernRunDeleted();
|
|
38207
39047
|
await modernHandler.close();
|
|
39048
|
+
permissionBroker.dispose();
|
|
38208
39049
|
httpServer.closeAllConnections();
|
|
38209
39050
|
await closed;
|
|
38210
39051
|
}
|
|
@@ -38230,9 +39071,14 @@ async function ownDaemonAlreadyRunning() {
|
|
|
38230
39071
|
}
|
|
38231
39072
|
async function runDaemon(options = {}) {
|
|
38232
39073
|
const log = (line) => console.error(line);
|
|
38233
|
-
const
|
|
39074
|
+
const permissionBroker = new WorkflowPermissionBroker();
|
|
39075
|
+
const runner = createAcpRunner({
|
|
39076
|
+
onPermissionRequest: permissionBroker.resolver,
|
|
39077
|
+
enforceToolPolicyBeforePermissionResolver: true
|
|
39078
|
+
});
|
|
39079
|
+
permissionBroker.attach(runner);
|
|
38234
39080
|
const supersede = options.supersede ?? false;
|
|
38235
|
-
const instanceId =
|
|
39081
|
+
const instanceId = randomUUID6();
|
|
38236
39082
|
let daemon;
|
|
38237
39083
|
const sessionTtlMs = envInt(SESSION_IDLE_TTL_ENV, SESSION_IDLE_TTL_MS);
|
|
38238
39084
|
const replDrainBoundMs = envInt(REPL_DRAIN_BOUND_ENV, REPL_DRAIN_BOUND_MS);
|
|
@@ -38242,7 +39088,7 @@ async function runDaemon(options = {}) {
|
|
|
38242
39088
|
return `port ${port} is still held by ${holder.legacy ? "a legacy " : ""}daemon pid ${holder.info.pid} (v${holder.info.version}, started ${holder.info.startedAt})`;
|
|
38243
39089
|
};
|
|
38244
39090
|
const evalBreakChannel = createEvalBreakChannel2();
|
|
38245
|
-
const daemonOptions = { runner, log, replDrainBoundMs, evalBreakChannel, ownInstanceId: instanceId };
|
|
39091
|
+
const daemonOptions = { runner, permissionBroker, log, replDrainBoundMs, evalBreakChannel, ownInstanceId: instanceId };
|
|
38246
39092
|
if (supersede) {
|
|
38247
39093
|
let port = options.port ?? 0;
|
|
38248
39094
|
try {
|
|
@@ -52269,7 +53115,12 @@ var ReplRelayStdioTransport = class {
|
|
|
52269
53115
|
|
|
52270
53116
|
// ../mcp-server/src/index.ts
|
|
52271
53117
|
async function main() {
|
|
52272
|
-
const
|
|
53118
|
+
const permissionBroker = new WorkflowPermissionBroker();
|
|
53119
|
+
const runner = createAcpRunner2({
|
|
53120
|
+
onPermissionRequest: permissionBroker.resolver,
|
|
53121
|
+
enforceToolPolicyBeforePermissionResolver: true
|
|
53122
|
+
});
|
|
53123
|
+
permissionBroker.attach(runner);
|
|
52273
53124
|
const projects = new WorkflowProjectRegistry(runner);
|
|
52274
53125
|
const defaultContext = projects.getOrCreate(process.cwd());
|
|
52275
53126
|
const replPresence = new ReplPresenceLedger(REPL_DRAIN_BOUND_MS);
|
|
@@ -52295,7 +53146,8 @@ async function main() {
|
|
|
52295
53146
|
replDrainBoundMs: REPL_DRAIN_BOUND_MS,
|
|
52296
53147
|
replEvalBreakChannel: evalBreakChannel,
|
|
52297
53148
|
protocolEra: era,
|
|
52298
|
-
disconnectReplClientOnClose: true
|
|
53149
|
+
disconnectReplClientOnClose: true,
|
|
53150
|
+
permissionBroker
|
|
52299
53151
|
});
|
|
52300
53152
|
activeServer = server;
|
|
52301
53153
|
activeEra = era;
|
|
@@ -52312,6 +53164,7 @@ async function main() {
|
|
|
52312
53164
|
replDefaultProjectDir: () => defaultContext.projectDir,
|
|
52313
53165
|
async disposeReplEvalBreakChannel() {
|
|
52314
53166
|
detachModernEvents();
|
|
53167
|
+
permissionBroker.dispose();
|
|
52315
53168
|
await projects.disposeReplStates();
|
|
52316
53169
|
replPresence.disconnectAll();
|
|
52317
53170
|
await evalBreakChannel.dispose();
|
|
@@ -52416,6 +53269,7 @@ export {
|
|
|
52416
53269
|
SHUTDOWN_DEADLINE_MS,
|
|
52417
53270
|
WORKFLOW_EVENTS_TOOL_NAME,
|
|
52418
53271
|
WORKFLOW_RUN_EVENTS_SCHEMA_VERSION,
|
|
53272
|
+
WorkflowPermissionBroker,
|
|
52419
53273
|
WorkflowProjectRegistry,
|
|
52420
53274
|
appResourceToolMeta,
|
|
52421
53275
|
authoringDocResource,
|