@tea-agent/loop-agent 0.43.0-next.17 → 0.43.0-next.19
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/AGENTS.md +1 -1
- package/CHANGELOG.md +68 -2309
- package/README.md +7 -0
- package/dist/application/dag/args.js +8 -0
- package/dist/application/task-lifecycle/advance.js +38 -7
- package/dist/build-stamp.json +3 -3
- package/dist/cli/command-definitions.js +2 -0
- package/dist/cli/program.js +3 -1
- package/dist/cli/update/init-surface-notifier.js +2 -0
- package/dist/cli/update/policy.js +2 -0
- package/dist/commands/cursor-prompt.js +2 -0
- package/dist/commands/dag-approve.js +2 -0
- package/dist/commands/dag-final-verification.js +2 -0
- package/dist/commands/dag-init-hybrid.js +2 -0
- package/dist/commands/dag-reconcile-tasks.js +2 -0
- package/dist/commands/dag-reject.js +2 -0
- package/dist/commands/dag-report.js +2 -0
- package/dist/commands/dag-rerun.js +2 -0
- package/dist/commands/dag-resume.js +2 -0
- package/dist/commands/dag-workflow-compile.js +2 -0
- package/dist/commands/dag-workflow-plan.js +2 -0
- package/dist/commands/dag-workflow-validate.js +2 -0
- package/dist/commands/delegate.js +2 -0
- package/dist/commands/examples.js +2 -0
- package/dist/commands/import-prd.js +2 -0
- package/dist/commands/init-model-catalog.js +2 -0
- package/dist/commands/init.js +19 -13
- package/dist/commands/instructions.js +2 -0
- package/dist/commands/knowledge.js +2 -0
- package/dist/commands/loop-benchmark.js +2 -0
- package/dist/commands/pi-prompt.js +2 -0
- package/dist/commands/pi-reuse-benchmark.js +2 -0
- package/dist/commands/promote-run.js +2 -0
- package/dist/commands/stats.js +1 -1
- package/dist/commands/study-init.js +2 -0
- package/dist/commands/task-advance.js +34 -0
- package/dist/commands/task-source-prepare.js +2 -0
- package/dist/commands/worktree-create.js +2 -0
- package/dist/commands/worktree-remove.js +2 -0
- package/dist/executors/dag-pi-executor.js +1640 -194
- package/dist/executors/pi-executor.js +85 -3
- package/dist/executors/pi-sdk-executor.js +18 -0
- package/dist/executors/shell-executor.js +92 -7
- package/dist/executors/shell-verification.js +3 -0
- package/dist/governance/exec-plans.js +6 -3
- package/dist/infrastructure/console/app-data.js +6 -0
- package/dist/shared/artifacts-core.js +2 -0
- package/dist/shared/backend-dogfood-preflight.js +47 -0
- package/dist/shared/dag-failure-category.js +3 -0
- package/dist/shared/git-progress.js +2 -0
- package/dist/shared/one-shot-prompt-args.js +2 -0
- package/dist/shared/operator/capabilities.js +180 -0
- package/dist/shared/package-metadata.js +6 -4
- package/dist/shared/pi-context-pressure/sift-bridge.js +1 -1
- package/dist/shared/reference-context.js +2 -0
- package/dist/task/config-types.js +29 -0
- package/dist/task/contract/project.js +9 -0
- package/dist/task/contract/recover.js +6 -0
- package/dist/task/contract/schema.js +17 -0
- package/dist/task/source-prepare/artifact-meta.js +9 -2
- package/dist/task/source-prepare/build-draft.js +60 -0
- package/dist/task/source-prepare/fragment-inventory.js +4 -1
- package/dist/task/source-prepare/parse-intent.js +36 -11
- package/dist/task/task-demand-routing.js +5 -2
- package/dist/worker/console/chat/browser-automation.js +468 -308
- package/dist/worker/console/chat/browser-routes.js +175 -57
- package/dist/worker/console/chat/explore-tools.js +5 -2
- package/dist/worker/console/chat/pi-mode-loop-isolation.js +155 -0
- package/dist/worker/console/chat/pi-runtime/custom-tools/browser-tools.js +115 -20
- package/dist/worker/console/chat/pi-runtime/custom-tools/operator-tools.js +24 -16
- package/dist/worker/console/chat/pi-runtime/custom-tools/scheduled-goal-tools.js +22 -0
- package/dist/worker/console/chat/pi-runtime/progressive-tools.js +195 -0
- package/dist/worker/console/chat/pi-runtime.js +95 -28
- package/dist/worker/console/chat/routes.js +20 -1
- package/dist/worker/console/chat/scheduled-goal-booking.js +59 -0
- package/dist/worker/console/chat/scheduled-goal-delivery.js +27 -0
- package/dist/worker/console/chat/scheduled-goal-request.js +190 -0
- package/dist/worker/console/chat/sdd-data-alignment.js +1 -1
- package/dist/worker/console/chat/session-mode.js +8 -4
- package/dist/worker/console/chat/session-store.js +42 -9
- package/dist/worker/console/chat/tool-preview.js +115 -0
- package/dist/worker/console/chat/tools.js +7 -1
- package/dist/worker/console/chat/turn-order.js +13 -0
- package/dist/worker/console/chat/turn-process.js +32 -30
- package/dist/worker/console/operator-actions.js +50 -0
- package/dist/worker/console/prd-intake-bridge.js +54 -1
- package/dist/worker/console/scheduled-goal-host.js +98 -0
- package/dist/worker/console/scheduled-goal-operation-adapter.js +127 -0
- package/dist/worker/console/server.js +15 -0
- package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-C4NXyedy.js → abnfDiagram-N423BO3Z-8-j6y-sd.js} +1 -1
- package/dist/worker/console/static/assets/{arc-NZ3qXvBI.js → arc-eoQiMvuk.js} +1 -1
- package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-COZSRvml.js → architectureDiagram-T3A2C74G-C4A3uMcI.js} +1 -1
- package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-Ck0Gxi9C.js → blockDiagram-VBNYF7ZC-D4zD2F-Q.js} +1 -1
- package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-BX5HQ4Ox.js → c4Diagram-5PPSVZJV-j1RkJziL.js} +1 -1
- package/dist/worker/console/static/assets/channel-ChE7y-cx.js +1 -0
- package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-CoviemSL.js → chunk-2GRJ4B5K-YBHmhik1.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-DbOdOkbZ.js → chunk-2Q5K7J3B-COfWyo9P.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-5RXB4S5H-BsG2pmdQ.js → chunk-5RXB4S5H-I99OUkHY.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-5VM5RSS4-DGdvrNm8.js → chunk-5VM5RSS4-XKxoJNJ4.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-BAy7Yd6y.js → chunk-6Q2QTUOP-DLT_cYx1.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-GF5L2VYU-D9UA7hUb.js → chunk-GF5L2VYU-CxcKZ9mV.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-JWPE2WC7-DPz7SZ8V.js → chunk-JWPE2WC7-V1EqXdjY.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-KBJHAD2P-BmuEOIh7.js → chunk-KBJHAD2P-DebTtdFp.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-RYQCIY6F-CIhBWnd8.js → chunk-RYQCIY6F-B-ivNRDf.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-XXDRQBXY-CScR6mDD.js → chunk-XXDRQBXY-DC_Ds11b.js} +1 -1
- package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-C01TCf2X.js +1 -0
- package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-C01TCf2X.js +1 -0
- package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-BjpfWaUr.js → cose-bilkent-JH36ORCC-sWEqKwIb.js} +1 -1
- package/dist/worker/console/static/assets/{cynefin-VYW2F7L2-BFQohJgT.js → cynefin-VYW2F7L2-BXa_dcu4.js} +1 -1
- package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-D3gzRJnS.js → cynefinDiagram-MW4NZA55-C-Mle84F.js} +1 -1
- package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-5eojkhoA.js → dagre-VZM6K2ZE-CXPDBITe.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-7IWD3JNH-CpD8LWu_.js → diagram-7IWD3JNH-CC-WJQfa.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-B8_4qJ2a.js → diagram-B4RE2ZJO-CDAV5Vs4.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-LBJQPF4R-HOsXf0eu.js → diagram-LBJQPF4R-CmFiAcNz.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-Q27KOJAE-BqwRwiWP.js → diagram-Q27KOJAE-DPBZHuyn.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-UB23O5K3-BRVCNZe1.js → diagram-UB23O5K3-jUlm_Ds3.js} +1 -1
- package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-Cvb1TgGh.js → ebnfDiagram-BXEA7PRR-DWhQ3mfY.js} +1 -1
- package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-DS0O0qG9.js → erDiagram-JOGREHBK-Tr2gMqet.js} +1 -1
- package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-BHIRvRr3.js → flowDiagram-UKHOOZJN-DJjVQHPA.js} +1 -1
- package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-DcCJ1JWx.js → ganttDiagram-PKOTCBZU-D74dQ4u0.js} +1 -1
- package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-B9ia5ony.js → gitGraphDiagram-DS77QQ5N-DwW0tZ0X.js} +1 -1
- package/dist/worker/console/static/assets/index-BWkIfcrK.css +1 -0
- package/dist/worker/console/static/assets/{index-wXlQohNs.js → index-Cdkvw_H6.js} +97 -97
- package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-3ogpgegn.js → infoDiagram-6WML65LV-ILCbxJyb.js} +1 -1
- package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-4tgpQ5SL.js → ishikawaDiagram-WSZJBQD7-DeuWBQ89.js} +1 -1
- package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-DNfgHqFx.js → journeyDiagram-NVQOT4AX-CF5ih8Fk.js} +1 -1
- package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-Dz7ngC8z.js → kanban-definition-27J2QSJJ-C7yOSuRO.js} +1 -1
- package/dist/worker/console/static/assets/{linear-DI7Jv62E.js → linear-BDZ9riWi.js} +1 -1
- package/dist/worker/console/static/assets/{mermaid.core-CQA4Nzmo.js → mermaid.core-7pKqYtpZ.js} +5 -5
- package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-CtsMc8Mf.js → mindmap-definition-FAOFIHXS-LeJDybSU.js} +1 -1
- package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-ByppE9yH.js → pegDiagram-VL7TDLO6-BJvT3pMD.js} +1 -1
- package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-B5PtgFgt.js → pieDiagram-7S7Q4E2Y-_rGqpMan.js} +1 -1
- package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-Cq4p0k2K.js → quadrantDiagram-CIZ2JOQS-DPcSv5aA.js} +1 -1
- package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-DjfkyljN.js → railroadDiagram-AXF67PYL-Drxx4hkJ.js} +1 -1
- package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-DzynNRSl.js → requirementDiagram-LRYGKXZP-BCTUdU4z.js} +1 -1
- package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-Cj7TCpTJ.js → sankeyDiagram-W5VNT64P-B6wzbZmB.js} +1 -1
- package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-C73C6ykA.js → sequenceDiagram-SI44F4Z6-BGt8d3QQ.js} +1 -1
- package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-BiNLgN2x.js → sizeCapture-X5ZJPWSS-7nlhJKo7.js} +1 -1
- package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-UwvjS64-.js → stateDiagram-OKZ733FA-Cv2stqMA.js} +1 -1
- package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-DC7V5vcq.js +1 -0
- package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-CC7DH98r.js → swimlanes-SLNWSIFB-qDAo4Yc1.js} +2 -2
- package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-Bwy4QUTO.js +8 -0
- package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-LSBXTR70.js → timeline-definition-Z64GVDOM-CKbDNKTr.js} +1 -1
- package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-BAuxWwGP.js → vennDiagram-T6HMQDX7-DI-9EHic.js} +1 -1
- package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y--E5_gjZx.js → wardleyDiagram-T6FBY63Y-BrzzRDpX.js} +1 -1
- package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-dJWNmyzF.js → xychartDiagram-ELKLHX3M-BclH5hGh.js} +1 -1
- package/dist/worker/console/static/index.html +2 -2
- package/dist/worker/console/static-src/operator-chat/chat-sse-events.js +41 -11
- package/dist/worker/console/static-src/operator-chat/compaction-message.js +3 -17
- package/dist/worker/console/static-src/operator-chat/slash-palette-nav.js +15 -5
- package/dist/worker/console/static-src/operator-chat/timeline-merge.js +29 -0
- package/dist/worker/console/static-src/operator-chat/useChatThread.js +2 -5
- package/dist/worker/console/static-src/operator-chat/useRepoBrowser.js +2 -0
- package/dist/worker/console/static-src/prd-file-import.js +3 -1
- package/dist/worker/console/workspace-context.js +17 -1
- package/dist/worker/delivery/git-transaction.js +2 -0
- package/dist/worker/feature/fullstack-validate.js +2 -0
- package/dist/worker/loop-agent/loop-agent-client.js +8 -2
- package/dist/worker/materialize/harness-task-materializer.js +4 -1
- package/dist/worker/metrics/projector.js +1 -1
- package/dist/worker/observability/event-store.js +4 -1
- package/dist/worker/observability/read-model.js +4 -1
- package/dist/worker/observe/node-transparency.js +23 -1
- package/dist/worker/observe/routes.js +4 -0
- package/dist/worker/observe/static/operator-chrome.js +3 -1
- package/dist/worker/outcomes/declared-artifacts.js +2 -0
- package/dist/worker/preflight.js +3 -0
- package/dist/worker/scheduler/scheduled-goal-dispatch.js +117 -0
- package/dist/worker/scheduler/scheduled-goal-evidence.js +167 -0
- package/dist/worker/scheduler/scheduled-goal-recovery.js +62 -0
- package/dist/worker/scheduler/scheduled-goal-store.js +699 -0
- package/dist/worker/scheduler/scheduled-goal-supervisor.js +132 -0
- package/dist/worker/scheduler/scheduled-goal-time.js +102 -0
- package/dist/worker/scheduler/scheduled-goal-types.js +95 -0
- package/dist/worker/task-spec/validate.js +4 -1
- package/dist/workflows/dag/backend-test-markdown-workflow.js +6 -24
- package/dist/workflows/dag/backend-test-plan-protocol.js +82 -5
- package/dist/workflows/dag/dag-retry-schema.js +11 -0
- package/dist/workflows/dag/decision-envelope.js +2 -0
- package/dist/workflows/dag/dynamic-runtime/shared.js +2 -2
- package/dist/workflows/dag/frontend-closeout.js +4 -2
- package/dist/workflows/dag/frontend-committed-facts.js +461 -0
- package/dist/workflows/dag/frontend-durable-tools.js +15 -3
- package/dist/workflows/dag/frontend-implementation-contract.js +365 -8
- package/dist/workflows/dag/frontend-plan-canary.js +53 -0
- package/dist/workflows/dag/frontend-plan-decision-contract.js +803 -0
- package/dist/workflows/dag/frontend-plan-render.js +0 -2
- package/dist/workflows/dag/frontend-prewrite-gate.js +3 -3
- package/dist/workflows/dag/frontend-provider-capability-matrix.js +8 -61
- package/dist/workflows/dag/frontend-recovery-run.js +57 -0
- package/dist/workflows/dag/frontend-review-context.js +43 -70
- package/dist/workflows/dag/frontend-risk.js +92 -10
- package/dist/workflows/dag/frontend-session-budget.js +117 -3
- package/dist/workflows/dag/frontend-shape.js +11 -55
- package/dist/workflows/dag/frontend-test-execution-evidence.js +35 -10
- package/dist/workflows/dag/frontend-typed-event-store.js +32 -25
- package/dist/workflows/dag/frontend-verification-trace.js +25 -12
- package/dist/workflows/dag/frontend-writer-admission.js +3 -47
- package/dist/workflows/dag/frontend-writer-status.js +0 -23
- package/dist/workflows/dag/init-hybrid.js +202 -111
- package/dist/workflows/dag/interrupt-request.js +2 -0
- package/dist/workflows/dag/lifecycle.js +11 -2
- package/dist/workflows/dag/node-execution.js +50 -13
- package/dist/workflows/dag/reconcile-run.js +2 -0
- package/dist/workflows/dag/repair-artifact.js +3 -1
- package/dist/workflows/dag/report.js +2 -0
- package/dist/workflows/dag/rerun-plan.js +10 -0
- package/dist/workflows/dag/rerun-task.js +79 -1
- package/dist/workflows/dag/retry-policy.js +18 -0
- package/dist/workflows/dag/scheduler.js +2 -4
- package/dist/workflows/dag/types.js +44 -6
- package/dist/workflows/dag/validate.js +4 -0
- package/docs/README.md +1 -0
- package/docs/governance/README.md +1 -0
- package/docs/init-surface.manifest.json +1 -0
- package/docs/operations/README.md +2 -0
- package/docs/templates/README.md +1 -1
- package/docs/templates/agent-dag.schema.json +2 -2
- package/docs/templates/backend-test-dag.json +14 -10
- package/docs/templates/frontend-implementation-contract.schema.json +0 -7
- package/docs/templates/frontend-implementation-dag.json +8 -9
- package/package.json +8 -3
- package/skills/frontend-bounded-implement/SKILL.md +3 -4
- package/skills/frontend-design-review/SKILL.md +7 -12
- package/skills/frontend-design-review/references/review-checklist.md +7 -7
- package/skills/frontend-plan/SKILL.md +8 -18
- package/skills/frontend-plan/references/decision-contract.md +19 -26
- package/skills/frontend-review/SKILL.md +21 -25
- package/skills/frontend-review/references/review-findings.md +48 -24
- package/dist/worker/console/static/assets/channel-BxdTlb_5.js +0 -1
- package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-_ByA1Nf8.js +0 -1
- package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-_ByA1Nf8.js +0 -1
- package/dist/worker/console/static/assets/index-B9goN3S5.css +0 -1
- package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-nLgMZ0D3.js +0 -1
- package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-BcYqTady.js +0 -8
- package/dist/workflows/dag/frontend-shadow-dual-write.js +0 -975
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { prepareScheduledGoalDraft } from "../../scheduler/scheduled-goal-dispatch.js";
|
|
3
|
+
import { scheduledGoalDraftSchema } from "../../scheduler/scheduled-goal-types.js";
|
|
4
|
+
import { scheduledGoalHash } from "../../scheduler/scheduled-goal-store.js";
|
|
5
|
+
import { readScheduledGoalResult } from "../../scheduler/scheduled-goal-recovery.js";
|
|
6
|
+
export const scheduledGoalBookingSchema = scheduledGoalDraftSchema.omit({ prepared: true, controllerRef: true }).extend({ chatSessionRef: z.string().regex(/^[a-zA-Z0-9_-]+$/) });
|
|
7
|
+
export const scheduledGoalConfirmationSchema = z.object({
|
|
8
|
+
goalId: z.string().min(1), stateVersion: z.number().int().positive(),
|
|
9
|
+
envelopeHash: z.string().regex(/^[a-f0-9]{64}$/),
|
|
10
|
+
}).strict();
|
|
11
|
+
/** Only non-capability fields are returned to Chat/browser. */
|
|
12
|
+
export function projectScheduledGoalBooking(goal) {
|
|
13
|
+
const { prepared: _prepared, controllerRef, ...scope } = goal.frozen;
|
|
14
|
+
return {
|
|
15
|
+
goalId: goal.goalId, stateVersion: goal.stateVersion, goalRevision: goal.goalRevision,
|
|
16
|
+
envelopeHash: goal.envelopeHash, state: goal.state, scope, controllerRef,
|
|
17
|
+
confirmationRequired: goal.state === "planned",
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
/** Preparation is not authorization, even when the clock is already due. */
|
|
21
|
+
export async function prepareScheduledGoalBooking(input, deps, resolveFinalTime) {
|
|
22
|
+
const parsed = scheduledGoalBookingSchema.parse(input);
|
|
23
|
+
const session = await deps.sessions.get(parsed.chatSessionRef);
|
|
24
|
+
if (!session || session.state !== "active")
|
|
25
|
+
throw new Error("booking requires an active Chat session");
|
|
26
|
+
const admitted = await prepareScheduledGoalDraft(parsed, deps.client);
|
|
27
|
+
// High-level relative time starts after slow strict admission, not before it.
|
|
28
|
+
const frozen = resolveFinalTime ? scheduledGoalDraftSchema.parse({ ...admitted, time: resolveFinalTime() }) : admitted;
|
|
29
|
+
const existing = (await deps.goals.list()).find((goal) => goal.frozen.managedTaskId === frozen.managedTaskId && goal.state === "planned" &&
|
|
30
|
+
scheduledGoalHash(goal.frozen) === scheduledGoalHash(frozen));
|
|
31
|
+
const goal = existing ?? await deps.goals.createDraft(frozen);
|
|
32
|
+
return projectScheduledGoalBooking(goal);
|
|
33
|
+
}
|
|
34
|
+
export async function confirmScheduledGoalBooking(input, deps, human) {
|
|
35
|
+
// Provenance is supplied by the authenticated route, never parsed from model input.
|
|
36
|
+
if (human.source !== "human-ui" || !human.requestId?.trim())
|
|
37
|
+
throw new Error("human confirmation required");
|
|
38
|
+
const parsed = scheduledGoalConfirmationSchema.parse(input);
|
|
39
|
+
const goal = await deps.goals.get(parsed.goalId);
|
|
40
|
+
if (goal.approval?.approvalRef === human.requestId && goal.approval.envelopeHash === parsed.envelopeHash &&
|
|
41
|
+
goal.approval.approvedVersion === parsed.stateVersion)
|
|
42
|
+
return projectScheduledGoalBooking(goal);
|
|
43
|
+
const session = await deps.sessions.get(goal.frozen.chatSessionRef);
|
|
44
|
+
if (!session || session.state !== "active")
|
|
45
|
+
throw new Error("booking requires an active Chat session");
|
|
46
|
+
if (goal.envelopeHash !== parsed.envelopeHash || goal.stateVersion !== parsed.stateVersion || goal.state !== "planned")
|
|
47
|
+
throw new Error("booking confirmation binding mismatch");
|
|
48
|
+
// Revalidate controller, strict gate, Task and scope immediately before approval.
|
|
49
|
+
const { prepared: _prepared, controllerRef: _controller, ...scope } = goal.frozen;
|
|
50
|
+
const fresh = await prepareScheduledGoalDraft(scope, deps.client);
|
|
51
|
+
if (scheduledGoalHash(fresh) !== scheduledGoalHash(goal.frozen))
|
|
52
|
+
throw new Error("booking preparation drift");
|
|
53
|
+
const approved = await deps.goals.approve(goal.goalId, parsed.stateVersion, parsed.envelopeHash, human.requestId);
|
|
54
|
+
return projectScheduledGoalBooking(approved);
|
|
55
|
+
}
|
|
56
|
+
export async function getScheduledGoalBooking(goalId, goals) {
|
|
57
|
+
const goal = await goals.get(goalId);
|
|
58
|
+
return { ...projectScheduledGoalBooking(goal), result: await readScheduledGoalResult(goalId, goals) };
|
|
59
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { scheduledGoalDeliveryKey } from "../../scheduler/scheduled-goal-store.js";
|
|
2
|
+
/** The durable Chat record deduplicates a retry after ledger acknowledgement is lost.
|
|
3
|
+
* A missing Chat never gets recreated. The goal remains available through its ledger.
|
|
4
|
+
*/
|
|
5
|
+
export async function deliverScheduledGoalResult(goal, goals, sessions) {
|
|
6
|
+
const key = scheduledGoalDeliveryKey(goal);
|
|
7
|
+
if (goal.deliveryKey === key && goal.deliveryState === "delivered")
|
|
8
|
+
return;
|
|
9
|
+
const evidence = goal.evidence.at(-1);
|
|
10
|
+
const states = {
|
|
11
|
+
accepted: "已验收", cancelled: "已取消", blocked: "已停止", budget_exhausted: "预算用尽", unknown: "需要核对",
|
|
12
|
+
failed: "未通过", pending: "待处理", stale: "证据已失效", succeeded: "通过",
|
|
13
|
+
};
|
|
14
|
+
const label = (value) => states[value] ?? value;
|
|
15
|
+
const text = [
|
|
16
|
+
`预约目标:${goal.frozen.originalGoal}`,
|
|
17
|
+
`目标状态:${label(goal.state)};验收:${label(goal.acceptanceState)}。已执行 ${goal.intents.length} 轮。`,
|
|
18
|
+
...(goal.reasonCode ? ["停止原因与需要核对的运行记录,可在本会话的预约面板查看。"] : []),
|
|
19
|
+
...(evidence ? evidence.assessment.criteria.map((ac) => {
|
|
20
|
+
const criterion = goal.frozen.acceptance.criteria.find((item) => item.acId === ac.acId);
|
|
21
|
+
return `${ac.acId} · ${criterion?.description ?? ac.acId}:${label(ac.status)}${ac.exitCode !== 0 ? `(退出码 ${ac.exitCode ?? "未知"})` : ""}。`;
|
|
22
|
+
}) : []),
|
|
23
|
+
`预约编号:${goal.goalId}。证据和历史保留在预约面板;删除会话不会删除运行事实。`,
|
|
24
|
+
].join("\n\n");
|
|
25
|
+
const delivered = await sessions.appendScheduledGoalResult(goal.frozen.chatSessionRef, key, text);
|
|
26
|
+
await goals.recordDelivery(goal.goalId, key, delivered ? "delivered" : "unavailable");
|
|
27
|
+
}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { promisify } from "node:util";
|
|
3
|
+
import { mkdir, open, readFile, realpath, rename, unlink, writeFile } from "node:fs/promises";
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
import { getTaskPaths } from "../../../task/runtime.js";
|
|
8
|
+
import { scheduledGoalDraftSchema, scheduledGoalTimeSchema } from "../../scheduler/scheduled-goal-types.js";
|
|
9
|
+
import { resolveScheduledGoalTime } from "../../scheduler/scheduled-goal-time.js";
|
|
10
|
+
import { ScheduledGoalStore, scheduledGoalHash } from "../../scheduler/scheduled-goal-store.js";
|
|
11
|
+
import { captureScheduledGoalTree } from "../../scheduler/scheduled-goal-evidence.js";
|
|
12
|
+
import { getScheduledGoalBooking, prepareScheduledGoalBooking } from "./scheduled-goal-booking.js";
|
|
13
|
+
const execFileAsync = promisify(execFile);
|
|
14
|
+
const protectedPaths = [".harness/**", "node_modules/**", ".git/**"];
|
|
15
|
+
const relativePath = z.string().trim().min(1).max(500).refine((value) => !path.isAbsolute(value) && !/^[A-Za-z]:/.test(value) && !value.includes("\\") &&
|
|
16
|
+
!value.split("/").some((part) => part === ".." || part === "." || part === "") && !value.startsWith("-"), "use a relative repository path without traversal");
|
|
17
|
+
const scheduleSchema = z.object({
|
|
18
|
+
delayMinutes: z.number().positive().max(525600).optional().describe("Delay AFTER preparation finishes; use for '3 minutes later'. The confirmation card shows the resulting exact time."),
|
|
19
|
+
localAt: z.string().regex(/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}$/).optional().describe("Explicit local date/time YYYY-MM-DD HH:mm; never silently move a past date."),
|
|
20
|
+
timezone: z.string().min(1).optional().describe("IANA timezone, e.g. Asia/Shanghai for Beijing. Defaults to the Console host timezone."),
|
|
21
|
+
fold: z.enum(["earlier", "later"]).optional(),
|
|
22
|
+
allowedHours: z.array(z.string()).optional().describe("Local allowed windows; default [] means all day."),
|
|
23
|
+
startGraceMinutes: z.number().positive().max(1440).optional(),
|
|
24
|
+
maxDurationMinutes: z.number().positive().max(1440).optional(),
|
|
25
|
+
}).strict().refine((value) => (value.delayMinutes !== undefined) !== (value.localAt !== undefined), "choose exactly one of delayMinutes or localAt");
|
|
26
|
+
/** The model supplies business meaning, never runtime identity or authorization. */
|
|
27
|
+
export const scheduledTaskRequestSchema = z.object({
|
|
28
|
+
originalGoal: z.string().trim().min(1).max(24000).describe("Faithfully preserve the complete user goal and constraints. Do not add unrequested failure cases, mocks, filenames or acceptance obligations; preserve real-service testing requirements."),
|
|
29
|
+
workflow: scheduledGoalDraftSchema.shape.workflow,
|
|
30
|
+
allowedPaths: z.array(relativePath).min(1).max(100).describe("Business outputs in the CURRENT project directory. For a read-only inspection, allow only a report such as scheduled-report.md, never .harness/."),
|
|
31
|
+
forbiddenPaths: z.array(relativePath).max(100).optional(),
|
|
32
|
+
acceptance: scheduledGoalDraftSchema.shape.acceptance.describe("Use minimal independent executable checks with AC-1, AC-2 IDs. Each command must exit nonzero on failure. For backend-test, acceptance must only inspect the finished run and must never invoke pytest. Prefer an existing read-only verification command or test -s report.md. Do not invent extra requirements, language-specific grep checks, shell pipelines, command substitution, redirects or compound shell statements. The host already enforces write scope."),
|
|
33
|
+
budget: scheduledGoalDraftSchema.shape.budget.optional().describe("Omit for ordinary tasks: defaults to one DAG run, one goal attempt and one supervisor call. maxTurns counts goal attempts, NOT model tool calls; maxSupervisorCalls does NOT count polling. Always displayed before confirmation."),
|
|
34
|
+
schedule: scheduleSchema,
|
|
35
|
+
}).strict();
|
|
36
|
+
export function resolveScheduledTaskTime(input, now) {
|
|
37
|
+
const schedule = scheduleSchema.parse(input);
|
|
38
|
+
const timezone = schedule.timezone ?? Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
39
|
+
const executeAtUtc = schedule.localAt
|
|
40
|
+
? resolveScheduledGoalTime({ localAt: schedule.localAt, timezone, fold: schedule.fold })
|
|
41
|
+
: new Date(now.getTime() + schedule.delayMinutes * 60000).toISOString();
|
|
42
|
+
if (Date.parse(executeAtUtc) <= now.getTime())
|
|
43
|
+
throw new Error("requested time is in the past; provide a new future time (不会自动顺延)");
|
|
44
|
+
const latestStart = Date.parse(executeAtUtc) + (schedule.startGraceMinutes ?? 15) * 60000;
|
|
45
|
+
const stop = latestStart + (schedule.maxDurationMinutes ?? 60) * 60000;
|
|
46
|
+
return scheduledGoalTimeSchema.parse({ executeAtUtc, latestStartUtc: new Date(latestStart).toISOString(),
|
|
47
|
+
stopAtUtc: new Date(stop).toISOString(), expiresAt: new Date(stop).toISOString(), timezone,
|
|
48
|
+
allowedHours: schedule.allowedHours ?? [], misfirePolicy: "run-immediately" });
|
|
49
|
+
}
|
|
50
|
+
const git = async (cwd, ...args) => (await execFileAsync("git", ["-C", cwd, ...args], { encoding: "utf8", timeout: 30000, maxBuffer: 4 * 1024 * 1024 })).stdout.trim();
|
|
51
|
+
const sameSet = (a, b) => JSON.stringify([...new Set(a)].sort()) === JSON.stringify([...new Set(b)].sort());
|
|
52
|
+
function assertScheduledAcceptanceDoesNotRepeatBackendTests(request) {
|
|
53
|
+
if (request.workflow !== "backend-test")
|
|
54
|
+
return;
|
|
55
|
+
const repeated = request.acceptance.criteria.find((criterion) => /(?:^|\s)(?:python(?:3)?\s+-m\s+)?pytest\b/i.test(criterion.command));
|
|
56
|
+
if (repeated)
|
|
57
|
+
throw new Error(`backend-test acceptance must not invoke pytest; ${repeated.acId} must inspect the completed run instead`);
|
|
58
|
+
}
|
|
59
|
+
/** Synchronous PREPARATION only. CLI calls are bounded and NEVER approve a DAG.
|
|
60
|
+
* A durable exclusive request marker prevents retries from creating duplicate Tasks
|
|
61
|
+
* or overwriting imported source. Unknown interrupted preparation is not reclaimed.
|
|
62
|
+
*/
|
|
63
|
+
export async function prepareScheduledTask(input, deps) {
|
|
64
|
+
const request = scheduledTaskRequestSchema.parse(input);
|
|
65
|
+
assertScheduledAcceptanceDoesNotRepeatBackendTests(request);
|
|
66
|
+
for (const ref of request.allowedPaths) {
|
|
67
|
+
if (/^(?:\.harness|\.git|node_modules)(?:\/|$)/.test(ref) || ref.includes("*") && !/^[\w.-]+\//.test(ref))
|
|
68
|
+
throw new Error(`protected or unbounded output path ${ref}; use an ordinary bounded report/output path, never runtime directories`);
|
|
69
|
+
}
|
|
70
|
+
if (!/^[a-zA-Z0-9_-]+$/.test(deps.sessionId) || (await deps.sessions.get(deps.sessionId))?.state !== "active")
|
|
71
|
+
throw new Error("preparation requires an active bound Chat session");
|
|
72
|
+
const identity = deps.client.getIdentity();
|
|
73
|
+
if (!identity)
|
|
74
|
+
throw new Error("preparation requires a pinned controller");
|
|
75
|
+
const repoRoot = await realpath(deps.repoRoot);
|
|
76
|
+
const now = deps.now ?? (() => new Date());
|
|
77
|
+
const key = scheduledGoalHash({ repoRoot, sessionId: deps.sessionId, request });
|
|
78
|
+
// Keep generated paths compact: runtimes/extensions may encode the whole cwd
|
|
79
|
+
// into one filename. The full hash below still verifies receipt identity.
|
|
80
|
+
const directory = path.join(deps.preparationRoot, key.slice(0, 24));
|
|
81
|
+
const recordPath = path.join(directory, "preparation.json");
|
|
82
|
+
const goals = new ScheduledGoalStore(repoRoot);
|
|
83
|
+
const existing = await readFile(recordPath, "utf8").then((text) => JSON.parse(text)).catch((error) => {
|
|
84
|
+
if (error.code === "ENOENT")
|
|
85
|
+
return undefined;
|
|
86
|
+
throw error;
|
|
87
|
+
});
|
|
88
|
+
if (existing) {
|
|
89
|
+
if (existing.version !== 1 || existing.requestHash !== key)
|
|
90
|
+
throw new Error("preparation record binding mismatch");
|
|
91
|
+
if (existing.goalId)
|
|
92
|
+
return getScheduledGoalBooking(existing.goalId, goals);
|
|
93
|
+
// Covers a crash after the goal ledger commit but before the local receipt.
|
|
94
|
+
const committed = (await goals.list()).find((goal) => goal.frozen.managedTaskId === existing.taskId && goal.frozen.chatSessionRef === deps.sessionId);
|
|
95
|
+
if (committed)
|
|
96
|
+
return getScheduledGoalBooking(committed.goalId, goals);
|
|
97
|
+
throw new Error(`previous preparation ${existing.stage}: ${existing.error ?? "still running or interrupted; do not duplicate or edit its artifacts"}; evidence: ${recordPath}`);
|
|
98
|
+
}
|
|
99
|
+
// Replays return their durable result even after the requested time has passed.
|
|
100
|
+
// New requests validate time before creating artifacts; relative time is also
|
|
101
|
+
// resolved after preparation so preparation cannot consume the delay.
|
|
102
|
+
resolveScheduledTaskTime(request.schedule, now());
|
|
103
|
+
// Check before creating a Task or receipt; never clean or reset the user's workspace.
|
|
104
|
+
const base = await git(repoRoot, "rev-parse", "HEAD");
|
|
105
|
+
const initial = await captureScheduledGoalTree(repoRoot, base, request.allowedPaths, protectedPaths);
|
|
106
|
+
if (initial.changedPaths.length)
|
|
107
|
+
throw new Error(`current workspace has uncommitted changes: ${initial.changedPaths.slice(0, 10).join(", ")}. Resolve them before booking; do not automatically commit, stash or reset user changes.`);
|
|
108
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
109
|
+
const lockPath = path.join(directory, "preparing.lock");
|
|
110
|
+
const lock = await open(lockPath, "wx", 0o600).catch((error) => {
|
|
111
|
+
if (error.code === "EEXIST")
|
|
112
|
+
throw new Error("preparation already running; do not duplicate or take over");
|
|
113
|
+
throw error;
|
|
114
|
+
});
|
|
115
|
+
const record = { version: 1, requestHash: key, stage: "workspace", taskId: `scheduled-${key.slice(0, 24)}`, worktree: repoRoot };
|
|
116
|
+
const persist = async () => {
|
|
117
|
+
const temporary = `${recordPath}.${randomUUID()}.tmp`;
|
|
118
|
+
await writeFile(temporary, JSON.stringify(record, null, 2), { mode: 0o600 });
|
|
119
|
+
await rename(temporary, recordPath);
|
|
120
|
+
};
|
|
121
|
+
let started = false;
|
|
122
|
+
try {
|
|
123
|
+
// Recheck after acquiring the lock: another request may have finished between
|
|
124
|
+
// our initial read and lock acquisition.
|
|
125
|
+
const raced = await readFile(recordPath, "utf8").catch((e) => { if (e.code === "ENOENT")
|
|
126
|
+
return undefined; throw e; });
|
|
127
|
+
if (raced)
|
|
128
|
+
throw new Error("preparation changed concurrently; retry reading the existing request");
|
|
129
|
+
started = true;
|
|
130
|
+
await persist();
|
|
131
|
+
const forbiddenPaths = [...new Set([...protectedPaths, ...(request.forbiddenPaths ?? [])])];
|
|
132
|
+
const prdPath = path.join(directory, "request.md");
|
|
133
|
+
const prd = ["# Scheduled task", "## Goal", request.originalGoal,
|
|
134
|
+
"## Execution context", `Execution and all outputs: current project directory ${record.worktree}.`,
|
|
135
|
+
"Inspect this project directly. Write only the authorized outputs here; for read-only inspection, write only the requested report. Implementation changes remain in this directory for the user to review. Do not create another worktree, copy outputs elsewhere, or reset/stash existing changes. The confirmed Git base must remain unchanged until execution finishes.",
|
|
136
|
+
"## Acceptance criteria", ...request.acceptance.criteria.map((ac) => `- ${ac.acId}: ${ac.description}\n Verification: ${ac.command}`),
|
|
137
|
+
"## Boundaries", `Workflow: ${request.workflow}; policy: ${request.acceptance.policy}.`,
|
|
138
|
+
`Allowed outputs: ${JSON.stringify(request.allowedPaths)}. Forbidden outputs: ${JSON.stringify(forbiddenPaths)}.`,
|
|
139
|
+
"Never modify imported requirements, .harness runtime, dependencies, Git history or configuration. No push, merge or publication. The host delivers the final result to the original Chat; do not implement a second delivery/scheduling mechanism.",
|
|
140
|
+
"## Verification", ...request.acceptance.criteria.map((ac) => ac.command), ""].join("\n\n");
|
|
141
|
+
await writeFile(prdPath, prd, { flag: "wx", mode: 0o600 });
|
|
142
|
+
const boundary = request.allowedPaths.flatMap((ref) => ["--allowed-path", ref])
|
|
143
|
+
.concat(forbiddenPaths.flatMap((ref) => ["--forbidden-path", ref]))
|
|
144
|
+
.concat(request.acceptance.criteria.flatMap((ac) => ["--verify", `${ac.acId}:${ac.command}`]));
|
|
145
|
+
for (let step = 0; step < 2; step++) {
|
|
146
|
+
record.stage = step === 0 ? "task-import" : "task-prepare";
|
|
147
|
+
await persist();
|
|
148
|
+
const args = ["task", "advance", record.taskId, ...(step === 0 ? ["Scheduled task", "--prd", prdPath] : []),
|
|
149
|
+
"--task-kind", request.workflow, ...boundary, "--json"];
|
|
150
|
+
const result = await deps.client.run(args, { cwd: record.worktree, artifactName: `${record.taskId}-${step}`, expectJson: true, timeoutMs: 300000 });
|
|
151
|
+
if (!result.ok || result.exitCode !== 0 || result.timedOut) {
|
|
152
|
+
const detail = JSON.stringify(result.json ?? result.stderr ?? "no CLI evidence").slice(0, 6000);
|
|
153
|
+
throw new Error(`${record.stage} failed: ${detail}. Correct the request and re-import through this tool; never edit source/references or runtime files.`);
|
|
154
|
+
}
|
|
155
|
+
const envelope = result.json;
|
|
156
|
+
if (envelope?.ok !== true)
|
|
157
|
+
throw new Error(`${record.stage}: missing successful CLI envelope`);
|
|
158
|
+
if (envelope.result?.lifecycleState === "awaiting-write-set-approval")
|
|
159
|
+
break;
|
|
160
|
+
}
|
|
161
|
+
record.stage = "booking";
|
|
162
|
+
await persist();
|
|
163
|
+
// Freeze actual strict-prepared path ordering/default restrictions. Never adopt
|
|
164
|
+
// a broader allowed set or drop a caller restriction to make admission pass.
|
|
165
|
+
const config = z.object({ taskKind: z.string(), allowedPaths: z.array(z.string()), forbiddenPaths: z.array(z.string()) }).parse(JSON.parse(await readFile(getTaskPaths(record.worktree, record.taskId).taskConfigPath, "utf8")));
|
|
166
|
+
if (config.taskKind !== request.workflow || !sameSet(config.allowedPaths, request.allowedPaths) || forbiddenPaths.some((ref) => !config.forbiddenPaths.includes(ref)))
|
|
167
|
+
throw new Error("prepared task scope differs from request; refusing to widen scope");
|
|
168
|
+
if (deps.client.getIdentity()?.packageFingerprint.value !== identity.packageFingerprint.value)
|
|
169
|
+
throw new Error("controller changed during preparation");
|
|
170
|
+
const booking = await prepareScheduledGoalBooking({ managedTaskId: record.taskId, originalGoal: request.originalGoal,
|
|
171
|
+
chatSessionRef: deps.sessionId, workflow: request.workflow, worktreeRef: record.worktree, frozenBase: base,
|
|
172
|
+
allowedPaths: config.allowedPaths, forbiddenPaths: config.forbiddenPaths, acceptance: request.acceptance,
|
|
173
|
+
budget: request.budget ?? { maxTurns: 1, maxDagRuns: 1, maxSupervisorCalls: 1 }, time: resolveScheduledTaskTime(request.schedule, now()),
|
|
174
|
+
}, { goals, client: deps.client, sessions: deps.sessions }, () => resolveScheduledTaskTime(request.schedule, now()));
|
|
175
|
+
record.goalId = booking.goalId;
|
|
176
|
+
record.stage = "planned";
|
|
177
|
+
await persist();
|
|
178
|
+
return booking;
|
|
179
|
+
}
|
|
180
|
+
catch (error) {
|
|
181
|
+
record.error = error instanceof Error ? error.message : String(error);
|
|
182
|
+
if (started)
|
|
183
|
+
await persist();
|
|
184
|
+
throw new Error(`Scheduled task preparation stopped at ${record.stage}: ${record.error}`);
|
|
185
|
+
}
|
|
186
|
+
finally {
|
|
187
|
+
await lock.close();
|
|
188
|
+
await unlink(lockPath);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
@@ -144,7 +144,7 @@ export class SddDataAlignmentError extends Error {
|
|
|
144
144
|
}
|
|
145
145
|
export function selectRandomSddSkillName(random = Math.random) {
|
|
146
146
|
const index = Math.min(SDD_SKILL_NAMES.length - 1, Math.max(0, Math.floor(random() * SDD_SKILL_NAMES.length)));
|
|
147
|
-
return SDD_SKILL_NAMES[index];
|
|
147
|
+
return SDD_SKILL_NAMES[index] ?? "";
|
|
148
148
|
}
|
|
149
149
|
export function normalizeSddSkillName(value, random = Math.random) {
|
|
150
150
|
if (value !== undefined && typeof value !== "string") {
|
|
@@ -74,7 +74,7 @@ export const PI_CHAT_SYSTEM_PROMPT_BASE = [
|
|
|
74
74
|
"Use read/write/edit/bash/grep/find/ls to inspect and change the workspace. apply_patch, full-tools, shell and coding-chat are denied.",
|
|
75
75
|
"Agent (Explore) is a built-in read-only subagent for path-uncertain codebase search. Do not use it for a known single-file read. Prefer safe-read/safe-grep for secret-safe probes.",
|
|
76
76
|
"ask_user_question pauses for a real user answer. todo_write tracks the current work and is restored after compression; it is not a workflow auto-continue signal. The persistent terminal tool is available.",
|
|
77
|
-
"
|
|
77
|
+
"Browser tools (navigate/search/snapshot/act/tabs/scroll/press/dialog/wait/screenshot) drive the workspace-controlled real browser shown in the Browser panel. Use refs from the latest page inspection for element actions; they never edit workspace files or execute page scripts. browser_snapshot means browser page inspection, not workspace snapshots.",
|
|
78
78
|
"Goal tools (get_goal / create_goal / update_goal) track the session's durable cross-turn objective. Create a Goal only when the user explicitly asks to start one; iterate in bounded rounds until complete or blocked.",
|
|
79
79
|
"This session keeps Console compression (L0/L1/L2, sift, strict checkpoint) and existing Aimax / SDD access. Do not create tasks, run DAGs, or start requirement interviews from this session.",
|
|
80
80
|
"Obey repository AGENTS.md, skills and extensions when they apply. Choosing Pi mode is not extra write authorization and does not bypass Console access control or output scrubbing.",
|
|
@@ -135,8 +135,10 @@ export function chatActiveToolBaseline(sessionMode) {
|
|
|
135
135
|
* not re-add operator actions via the extras pass (Goal tools are shared and
|
|
136
136
|
* part of the Pi baseline since 2026-09-10).
|
|
137
137
|
*/
|
|
138
|
-
export function computeChatActiveToolNames(session, sessionMode) {
|
|
139
|
-
const
|
|
138
|
+
export function computeChatActiveToolNames(session, sessionMode, exposedWorkflowTools) {
|
|
139
|
+
const exposure = sessionMode === "workflow" && exposedWorkflowTools
|
|
140
|
+
? new Set(exposedWorkflowTools.map(name => name.toLowerCase())) : undefined;
|
|
141
|
+
const baseline = chatActiveToolBaseline(sessionMode).filter(name => !exposure || !WORKFLOW_OPERATOR_TOOL_IDS.has(name.toLowerCase()) || exposure.has(name.toLowerCase()));
|
|
140
142
|
if (!session?.getAllTools)
|
|
141
143
|
return baseline;
|
|
142
144
|
const baselineLower = new Set(baseline.map((name) => name.toLowerCase()));
|
|
@@ -148,10 +150,12 @@ export function computeChatActiveToolNames(session, sessionMode) {
|
|
|
148
150
|
const lower = name.toLowerCase();
|
|
149
151
|
if (baselineLower.has(lower))
|
|
150
152
|
continue;
|
|
151
|
-
if (CHAT_EXTENSION_DENIED_TOOL_IDS.has(lower))
|
|
153
|
+
if (CHAT_EXTENSION_DENIED_TOOL_IDS.has(lower) || isOperatorChatToolDenied(name))
|
|
152
154
|
continue;
|
|
153
155
|
if (sessionMode === "pi" && WORKFLOW_OPERATOR_TOOL_IDS.has(lower))
|
|
154
156
|
continue;
|
|
157
|
+
if (exposure && WORKFLOW_OPERATOR_TOOL_IDS.has(lower) && !exposure.has(lower))
|
|
158
|
+
continue;
|
|
155
159
|
extras.push(name);
|
|
156
160
|
}
|
|
157
161
|
return extras.length > 0 ? [...baseline, ...extras] : baseline;
|
|
@@ -477,6 +477,24 @@ export class ChatSessionStore {
|
|
|
477
477
|
};
|
|
478
478
|
});
|
|
479
479
|
}
|
|
480
|
+
/** Idempotent persistent delivery, serialized with normal Chat updates. */
|
|
481
|
+
async appendScheduledGoalResult(sessionId, resultKey, text) {
|
|
482
|
+
if (!/^[a-zA-Z0-9_-]+$/.test(sessionId) || !/^[a-f0-9]{64}$/.test(resultKey))
|
|
483
|
+
throw new Error("invalid scheduled goal delivery identity");
|
|
484
|
+
return this.serialize(sessionId, async () => {
|
|
485
|
+
const record = await this.get(sessionId);
|
|
486
|
+
if (!record)
|
|
487
|
+
return false;
|
|
488
|
+
const id = `scheduled-goal-${resultKey}`;
|
|
489
|
+
if (record.messages.some((message) => message.id === id))
|
|
490
|
+
return true;
|
|
491
|
+
const at = new Date().toISOString();
|
|
492
|
+
record.messages.push({ id, role: "assistant", text, at });
|
|
493
|
+
record.updatedAt = at;
|
|
494
|
+
await this.persist(record);
|
|
495
|
+
return true;
|
|
496
|
+
});
|
|
497
|
+
}
|
|
480
498
|
async appendMessage(sessionId, message) {
|
|
481
499
|
return this.serialize(sessionId, async () => {
|
|
482
500
|
const record = await this.get(sessionId);
|
|
@@ -637,21 +655,36 @@ export async function runChatTurn(options) {
|
|
|
637
655
|
// never observes agent_settled before its accepted operation ref.
|
|
638
656
|
settledEvent = event;
|
|
639
657
|
}
|
|
658
|
+
else if (event.type === "message_end") {
|
|
659
|
+
// Persist the assistant bubble FIRST so the SSE frame and the restore
|
|
660
|
+
// projection share the same durable message id (2026-09-13). The text-
|
|
661
|
+
// match + 30s window in projectStoredMessagesWithEventOrder was the only
|
|
662
|
+
// bridge left between the two, and it mis-aligned on duplicate text.
|
|
663
|
+
let messageId;
|
|
664
|
+
try {
|
|
665
|
+
const stored = await store.appendMessage(sessionId, {
|
|
666
|
+
role: "assistant",
|
|
667
|
+
text: event.text,
|
|
668
|
+
...(event.content && event.content.length > 0
|
|
669
|
+
? { content: event.content }
|
|
670
|
+
: {}),
|
|
671
|
+
});
|
|
672
|
+
messageId = stored.id;
|
|
673
|
+
}
|
|
674
|
+
catch {
|
|
675
|
+
// Persistence failure must not swallow the SSE frame — the client
|
|
676
|
+
// still needs the terminal text even if the durable row is absent.
|
|
677
|
+
}
|
|
678
|
+
options.onEvent?.(messageId ? { ...event, messageId } : event);
|
|
679
|
+
}
|
|
640
680
|
else {
|
|
641
681
|
options.onEvent?.(event);
|
|
642
682
|
}
|
|
643
683
|
switch (event.type) {
|
|
644
684
|
case "message_update":
|
|
645
685
|
case "message_end":
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
role: "assistant",
|
|
649
|
-
text: event.text,
|
|
650
|
-
...(event.content && event.content.length > 0
|
|
651
|
-
? { content: event.content }
|
|
652
|
-
: {}),
|
|
653
|
-
}));
|
|
654
|
-
}
|
|
686
|
+
// message_update carries no durable row; message_end was already
|
|
687
|
+
// persisted + framed above. Nothing further to persist here.
|
|
655
688
|
break;
|
|
656
689
|
case "tool_call":
|
|
657
690
|
// Forwarded to the caller (SSE) for UI feedback. The actual tool
|
|
@@ -148,6 +148,115 @@ export function getToolPreview(args, options) {
|
|
|
148
148
|
return "";
|
|
149
149
|
return s.length > maxLen ? `${s.slice(0, maxLen)}…` : s;
|
|
150
150
|
}
|
|
151
|
+
/** DSH-style human-readable ask_user_question row (rowTitle「提问」). */
|
|
152
|
+
export function isAskUserQuestionTool(toolName) {
|
|
153
|
+
return (toolName ?? "").trim().toLowerCase() === "ask_user_question";
|
|
154
|
+
}
|
|
155
|
+
function normalizeOptionLabel(value) {
|
|
156
|
+
const record = asRecord(value);
|
|
157
|
+
if (!record)
|
|
158
|
+
return undefined;
|
|
159
|
+
const label = typeof record.label === "string" ? record.label.trim() : "";
|
|
160
|
+
return label || undefined;
|
|
161
|
+
}
|
|
162
|
+
function normalizeAskQuestion(value) {
|
|
163
|
+
const record = asRecord(value);
|
|
164
|
+
if (!record)
|
|
165
|
+
return undefined;
|
|
166
|
+
const id = typeof record.id === "string" ? record.id.trim() : "";
|
|
167
|
+
const question = typeof record.question === "string" ? record.question.trim() : "";
|
|
168
|
+
if (!id || !question)
|
|
169
|
+
return undefined;
|
|
170
|
+
const options = Array.isArray(record.options)
|
|
171
|
+
? record.options
|
|
172
|
+
.map((item) => {
|
|
173
|
+
const label = normalizeOptionLabel(item);
|
|
174
|
+
if (!label)
|
|
175
|
+
return undefined;
|
|
176
|
+
const description = typeof item === "object" && item !== null &&
|
|
177
|
+
"description" in item && typeof item.description === "string"
|
|
178
|
+
? item.description
|
|
179
|
+
: undefined;
|
|
180
|
+
return { label, ...(description && description.trim() ? { description: description.trim() } : {}) };
|
|
181
|
+
})
|
|
182
|
+
.filter((item) => Boolean(item))
|
|
183
|
+
: undefined;
|
|
184
|
+
return {
|
|
185
|
+
id,
|
|
186
|
+
question,
|
|
187
|
+
...(typeof record.header === "string" && record.header.trim()
|
|
188
|
+
? { header: record.header.trim() }
|
|
189
|
+
: {}),
|
|
190
|
+
...(typeof record.detail === "string" && record.detail.trim()
|
|
191
|
+
? { detail: record.detail.trim() }
|
|
192
|
+
: {}),
|
|
193
|
+
...(options && options.length > 0 ? { options } : {}),
|
|
194
|
+
...(record.multi_select === true || record.multiSelect === true
|
|
195
|
+
? { multiSelect: true }
|
|
196
|
+
: {}),
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
/** Project ask_user_question args (questions array) into readable views. */
|
|
200
|
+
export function parseAskUserQuestions(args) {
|
|
201
|
+
const input = parseArgs(args);
|
|
202
|
+
if (!input)
|
|
203
|
+
return [];
|
|
204
|
+
const raw = Array.isArray(input)
|
|
205
|
+
? input
|
|
206
|
+
: Array.isArray(input.questions)
|
|
207
|
+
? input.questions
|
|
208
|
+
: [];
|
|
209
|
+
return raw
|
|
210
|
+
.map(normalizeAskQuestion)
|
|
211
|
+
.filter((item) => Boolean(item));
|
|
212
|
+
}
|
|
213
|
+
/** Project ask_user_question ToolResult into answer views keyed by question id. */
|
|
214
|
+
export function parseAskUserAnswers(result) {
|
|
215
|
+
if (result === undefined || result === null)
|
|
216
|
+
return [];
|
|
217
|
+
const text = extractToolResultText(result);
|
|
218
|
+
if (!text)
|
|
219
|
+
return [];
|
|
220
|
+
let parsed;
|
|
221
|
+
try {
|
|
222
|
+
parsed = JSON.parse(text);
|
|
223
|
+
}
|
|
224
|
+
catch {
|
|
225
|
+
return [];
|
|
226
|
+
}
|
|
227
|
+
const record = asRecord(parsed);
|
|
228
|
+
const raw = record && Array.isArray(record.answers) ? record.answers : undefined;
|
|
229
|
+
if (!raw)
|
|
230
|
+
return [];
|
|
231
|
+
const out = [];
|
|
232
|
+
for (const entry of raw) {
|
|
233
|
+
const rec = entry && typeof entry === "object" && !Array.isArray(entry)
|
|
234
|
+
? entry
|
|
235
|
+
: undefined;
|
|
236
|
+
if (!rec || typeof rec.id !== "string")
|
|
237
|
+
continue;
|
|
238
|
+
const selected = Array.isArray(rec.selected)
|
|
239
|
+
? rec.selected.filter((item) => typeof item === "string").map((item) => item.trim()).filter(Boolean)
|
|
240
|
+
: [];
|
|
241
|
+
const custom = typeof rec.custom === "string" ? rec.custom.trim() : "";
|
|
242
|
+
out.push({ id: rec.id, selected, ...(custom ? { custom } : {}) });
|
|
243
|
+
}
|
|
244
|
+
return out;
|
|
245
|
+
}
|
|
246
|
+
/** "{answered}/{total} 已回答" summary; total from args questions, answered from result answers. */
|
|
247
|
+
export function getAskUserQuestionSummary(args, result) {
|
|
248
|
+
const questions = parseAskUserQuestions(args);
|
|
249
|
+
if (questions.length === 0)
|
|
250
|
+
return null;
|
|
251
|
+
const answers = parseAskUserAnswers(result);
|
|
252
|
+
let answered = 0;
|
|
253
|
+
for (const question of questions) {
|
|
254
|
+
const answer = answers.find((item) => item.id === question.id);
|
|
255
|
+
if (answer && (answer.selected.length > 0 || answer.custom))
|
|
256
|
+
answered += 1;
|
|
257
|
+
}
|
|
258
|
+
return { answered, total: questions.length };
|
|
259
|
+
}
|
|
151
260
|
/** Stable DSH-style tool row identity; unknown tools keep their real name. */
|
|
152
261
|
export function getToolPresentation(toolName) {
|
|
153
262
|
const raw = toolName?.trim() || "Tool";
|
|
@@ -191,6 +300,9 @@ export function getToolPresentation(toolName) {
|
|
|
191
300
|
if (name === "agent") {
|
|
192
301
|
return { kind: "search", label: "Explore" };
|
|
193
302
|
}
|
|
303
|
+
if (isAskUserQuestionTool(toolName)) {
|
|
304
|
+
return { kind: "tool", label: "提问" };
|
|
305
|
+
}
|
|
194
306
|
return { kind: "tool", label: raw };
|
|
195
307
|
}
|
|
196
308
|
/** A tool call that failed on its own. A call interrupted by Stop carries
|
|
@@ -213,6 +325,9 @@ export function getToolSectionLabels(toolName) {
|
|
|
213
325
|
if (name === "mcp" || name.startsWith("mcp_")) {
|
|
214
326
|
return { argsLabel: "参数", resultLabel: "结果" };
|
|
215
327
|
}
|
|
328
|
+
if (isAskUserQuestionTool(toolName)) {
|
|
329
|
+
return { argsLabel: "提问", resultLabel: "您的回答" };
|
|
330
|
+
}
|
|
216
331
|
return { argsLabel: "入参", resultLabel: "结果" };
|
|
217
332
|
}
|
|
218
333
|
/**
|
|
@@ -27,8 +27,14 @@ export const OPERATOR_CHAT_BUILTIN_CUSTOM_TOOLS = Object.freeze([
|
|
|
27
27
|
"scm",
|
|
28
28
|
"browser_navigate",
|
|
29
29
|
"browser_search",
|
|
30
|
-
"
|
|
30
|
+
"browser_snapshot",
|
|
31
31
|
"browser_act",
|
|
32
|
+
"browser_tabs",
|
|
33
|
+
"browser_scroll",
|
|
34
|
+
"browser_press",
|
|
35
|
+
"browser_dialog",
|
|
36
|
+
"browser_wait",
|
|
37
|
+
"browser_screenshot",
|
|
32
38
|
]);
|
|
33
39
|
/**
|
|
34
40
|
* Actions the model MAY invoke. Derived from the registry but filtered by the
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export function compareChatOrder(a, b) {
|
|
2
|
+
if (a.eventSeq !== undefined &&
|
|
3
|
+
b.eventSeq !== undefined &&
|
|
4
|
+
a.eventSeq !== b.eventSeq) {
|
|
5
|
+
return a.eventSeq - b.eventSeq;
|
|
6
|
+
}
|
|
7
|
+
if (a.createdAt !== b.createdAt)
|
|
8
|
+
return a.createdAt - b.createdAt;
|
|
9
|
+
// Same timestamp with mismatched sequence presence: keep the original
|
|
10
|
+
// insertion order (stable sort). Deciding here would re-order live SSE
|
|
11
|
+
// frames that happen to share a millisecond with a tool row.
|
|
12
|
+
return 0;
|
|
13
|
+
}
|