@piagent/platform 1.3.1 → 1.4.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/CHANGELOG.md +39 -0
- package/README.md +3 -3
- package/architecture/layers.json +96 -1
- package/docs/README.md +1 -0
- package/docs/architecture.md +1 -0
- package/docs/authority-manifest.md +1 -0
- package/docs/auto-delegation-policy.md +1 -0
- package/docs/capability-packs.md +1 -0
- package/docs/command-reference-vietnamese.md +5 -4
- package/docs/context-engine.md +1 -0
- package/docs/context-window-policy.md +1 -0
- package/docs/distribution-standard.md +8 -7
- package/docs/herdr-workflow.md +1 -0
- package/docs/mcp-and-tools.md +14 -9
- package/docs/memory-policy.md +1 -0
- package/docs/model-options.md +1 -0
- package/docs/oauth-providers.md +1 -0
- package/docs/operator-manual-vietnamese.md +15 -12
- package/docs/package-architecture-notes.md +1 -0
- package/docs/project-adapters.md +1 -0
- package/docs/project-onboarding.md +1 -0
- package/docs/publishing-for-teams.md +1 -0
- package/docs/quality-benchmark.md +1 -0
- package/docs/quickstart-vietnamese.md +3 -2
- package/docs/release-install-policy.md +7 -6
- package/docs/runtime-harness-standard.md +1 -0
- package/docs/runtime-policy-design.md +1 -0
- package/docs/runtime-quality-baseline.md +1 -0
- package/docs/security-redaction-benchmark.md +1 -0
- package/docs/security-threat-model.md +2 -1
- package/docs/subagent-orchestration-capabilities.md +1 -0
- package/docs/subagents-and-multiagent.md +1 -0
- package/docs/task-implementation-contract.md +1 -0
- package/docs/task-lifecycle-vietnamese.md +1 -0
- package/docs/team-onboarding.md +3 -2
- package/docs/third-party-neutrality.md +26 -0
- package/docs/usage-observability.md +1 -0
- package/docs/vercel-docs-site.md +1 -0
- package/docs/workflow-recipes.md +1 -0
- package/docs-site/architecture.html +1 -1
- package/docs-site/benchmark.html +1 -1
- package/docs-site/commands.html +1 -1
- package/docs-site/context-engine.html +1 -1
- package/docs-site/en/architecture.html +1 -1
- package/docs-site/en/benchmark.html +1 -1
- package/docs-site/en/commands.html +1 -1
- package/docs-site/en/context-engine.html +1 -1
- package/docs-site/en/index.html +1 -1
- package/docs-site/en/mcp-approval.html +1 -1
- package/docs-site/en/mcp-auth.html +1 -1
- package/docs-site/en/mcp-servers.html +1 -1
- package/docs-site/en/mcp.html +1 -1
- package/docs-site/en/permissions.html +1 -1
- package/docs-site/en/profiles.html +1 -1
- package/docs-site/en/quickstart.html +1 -1
- package/docs-site/en/runtime.html +1 -1
- package/docs-site/en/scope.html +1 -1
- package/docs-site/en/security.html +1 -1
- package/docs-site/en/team.html +1 -1
- package/docs-site/en/whats-new.html +1 -1
- package/docs-site/en/workflows.html +1 -1
- package/docs-site/index.html +1 -1
- package/docs-site/mcp-approval.html +1 -1
- package/docs-site/mcp-auth.html +1 -1
- package/docs-site/mcp-servers.html +1 -1
- package/docs-site/mcp.html +1 -1
- package/docs-site/permissions.html +1 -1
- package/docs-site/profiles.html +1 -1
- package/docs-site/quickstart.html +1 -1
- package/docs-site/runtime.html +1 -1
- package/docs-site/scope.html +1 -1
- package/docs-site/security.html +1 -1
- package/docs-site/team.html +1 -1
- package/docs-site/whats-new.html +1 -1
- package/docs-site/workflows.html +1 -1
- package/evals/fixtures/mutation-provenance-record.invalid.json +17 -0
- package/evals/fixtures/mutation-provenance-record.valid.json +27 -0
- package/evals/fixtures/piagent-webui/approval-v1.invalid.json +54 -0
- package/evals/fixtures/piagent-webui/approval-v1.valid.json +58 -0
- package/evals/fixtures/piagent-webui/attachment-v1.invalid.json +25 -0
- package/evals/fixtures/piagent-webui/attachment-v1.valid.json +25 -0
- package/evals/fixtures/piagent-webui/capabilities-v1.invalid.json +51 -0
- package/evals/fixtures/piagent-webui/capabilities-v1.valid.json +122 -0
- package/evals/fixtures/piagent-webui/commit-summary-v1.invalid.json +10 -0
- package/evals/fixtures/piagent-webui/commit-summary-v1.valid.json +25 -0
- package/evals/fixtures/piagent-webui/control-command-v1.invalid.json +37 -0
- package/evals/fixtures/piagent-webui/control-command-v1.valid.json +35 -0
- package/evals/fixtures/piagent-webui/diff-v1.invalid.json +13 -0
- package/evals/fixtures/piagent-webui/diff-v1.valid.json +141 -0
- package/evals/fixtures/piagent-webui/gateway-capabilities-v1.invalid.json +35 -0
- package/evals/fixtures/piagent-webui/gateway-capabilities-v1.valid.json +35 -0
- package/evals/fixtures/piagent-webui/gateway-protocol-v1.invalid.json +14 -0
- package/evals/fixtures/piagent-webui/gateway-protocol-v1.valid.json +14 -0
- package/evals/fixtures/piagent-webui/handoff-history-v1.invalid.json +16 -0
- package/evals/fixtures/piagent-webui/handoff-history-v1.valid.json +16 -0
- package/evals/fixtures/piagent-webui/model-catalog-v1.invalid.json +31 -0
- package/evals/fixtures/piagent-webui/model-catalog-v1.valid.json +43 -0
- package/evals/fixtures/piagent-webui/queue-v1.invalid.json +29 -0
- package/evals/fixtures/piagent-webui/queue-v1.valid.json +44 -0
- package/evals/fixtures/piagent-webui/recovery-history-v1.invalid.json +17 -0
- package/evals/fixtures/piagent-webui/recovery-history-v1.valid.json +20 -0
- package/evals/fixtures/piagent-webui/release-monitor-v1.invalid.json +12 -0
- package/evals/fixtures/piagent-webui/release-monitor-v1.valid.json +29 -0
- package/evals/fixtures/piagent-webui/review-state-v1.invalid.json +25 -0
- package/evals/fixtures/piagent-webui/review-state-v1.valid.json +38 -0
- package/evals/fixtures/piagent-webui/runtime-event-v2.invalid.json +49 -0
- package/evals/fixtures/piagent-webui/runtime-event-v2.valid.json +49 -0
- package/evals/fixtures/piagent-webui/session-catalog-v1.invalid.json +17 -0
- package/evals/fixtures/piagent-webui/session-catalog-v1.valid.json +58 -0
- package/evals/fixtures/piagent-webui/session-command-v1.invalid.json +19 -0
- package/evals/fixtures/piagent-webui/session-command-v1.valid.json +19 -0
- package/evals/fixtures/piagent-webui/snapshot-v1.invalid.json +5 -0
- package/evals/fixtures/piagent-webui/snapshot-v1.valid.json +191 -0
- package/evals/fixtures/piagent-webui/source-change-v1.invalid.json +57 -0
- package/evals/fixtures/piagent-webui/source-change-v1.valid.json +98 -0
- package/evals/fixtures/piagent-webui/source-mutation-v1.invalid.json +19 -0
- package/evals/fixtures/piagent-webui/source-mutation-v1.valid.json +38 -0
- package/evals/fixtures/piagent-webui/source-revert-v1.invalid.json +20 -0
- package/evals/fixtures/piagent-webui/source-revert-v1.valid.json +62 -0
- package/evals/fixtures/piagent-webui/subagent-tree-v1.invalid.json +26 -0
- package/evals/fixtures/piagent-webui/subagent-tree-v1.valid.json +39 -0
- package/evals/fixtures/piagent-webui/task-index-v1.invalid.json +15 -0
- package/evals/fixtures/piagent-webui/task-index-v1.valid.json +15 -0
- package/evals/fixtures/piagent-webui/task-timeline-v1.invalid.json +14 -0
- package/evals/fixtures/piagent-webui/task-timeline-v1.valid.json +16 -0
- package/evals/fixtures/piagent-webui/transcript-v1.invalid.json +35 -0
- package/evals/fixtures/piagent-webui/transcript-v1.valid.json +55 -0
- package/evals/fixtures/task-baseline-manifest.invalid.json +16 -0
- package/evals/fixtures/task-baseline-manifest.valid.json +41 -0
- package/evals/fixtures/verifier-file-snapshot.invalid.json +21 -0
- package/evals/fixtures/verifier-file-snapshot.valid.json +21 -0
- package/package.json +30 -3
- package/packages/piagent-core/benchmark/benchmark-candidate.d.ts +1 -0
- package/packages/piagent-core/benchmark/benchmark-forensics.d.ts +1 -0
- package/packages/piagent-core/benchmark/benchmark-ledger.d.ts +4 -0
- package/packages/piagent-core/benchmark/benchmark-record-validation.d.ts +1 -0
- package/packages/piagent-core/benchmark/benchmark-runtime.d.ts +1 -0
- package/packages/piagent-core/capabilities/capability-core.js +2 -2
- package/packages/piagent-core/capabilities/runtime-integrity.js +143 -0
- package/packages/piagent-core/extensions/piagent-guard.ts +62 -37
- package/packages/piagent-core/extensions/redaction-core.d.ts +2 -0
- package/packages/piagent-core/extensions/task-journal.js +30 -1
- package/packages/piagent-core/extensions/task-state.js +33 -36
- package/packages/piagent-core/mcp/mcp-server-catalog.js +5 -5
- package/packages/piagent-core/package.json +1 -1
- package/packages/piagent-core/runtime/hooks/session-start-hook.ts +2 -2
- package/packages/piagent-core/runtime/hooks/tool-call-hook.ts +5 -2
- package/packages/piagent-core/runtime/hooks/tool-result-hook.ts +20 -19
- package/packages/piagent-core/runtime/hooks/tool-result-metadata.ts +13 -0
- package/packages/piagent-core/runtime/input/chat-images.ts +2 -2
- package/packages/piagent-core/runtime/inspection/activity-event-adapter.ts +94 -0
- package/packages/piagent-core/runtime/inspection/approval-broker.ts +318 -0
- package/packages/piagent-core/runtime/inspection/commit-summary-projection.ts +59 -0
- package/packages/piagent-core/runtime/inspection/context-telemetry-inspection.ts +37 -0
- package/packages/piagent-core/runtime/inspection/criteria-links.ts +295 -0
- package/packages/piagent-core/runtime/inspection/diff-projection.ts +499 -0
- package/packages/piagent-core/runtime/inspection/git-filter-safety.ts +38 -0
- package/packages/piagent-core/runtime/inspection/git-numstat-adapter.ts +71 -0
- package/packages/piagent-core/runtime/inspection/git-status-adapter.ts +493 -0
- package/packages/piagent-core/runtime/inspection/git-tree-adapter.ts +108 -0
- package/packages/piagent-core/runtime/inspection/mcp-control.ts +10 -0
- package/packages/piagent-core/runtime/inspection/mutation-provenance-contract.ts +131 -0
- package/packages/piagent-core/runtime/inspection/mutation-provenance-recorder.ts +48 -0
- package/packages/piagent-core/runtime/inspection/mutation-provenance-store.ts +161 -0
- package/packages/piagent-core/runtime/inspection/project-runtime-inspection.ts +36 -0
- package/packages/piagent-core/runtime/inspection/review-state-contract.ts +108 -0
- package/packages/piagent-core/runtime/inspection/review-state-projection.ts +93 -0
- package/packages/piagent-core/runtime/inspection/review-state-store.ts +112 -0
- package/packages/piagent-core/runtime/inspection/runtime-event-store.ts +262 -0
- package/packages/piagent-core/runtime/inspection/same-process-bridge-proof.ts +103 -0
- package/packages/piagent-core/runtime/inspection/source-change-projection.ts +471 -0
- package/packages/piagent-core/runtime/inspection/source-evidence-contract.ts +139 -0
- package/packages/piagent-core/runtime/inspection/source-evidence-store.ts +315 -0
- package/packages/piagent-core/runtime/inspection/source-handoff-store.ts +70 -0
- package/packages/piagent-core/runtime/inspection/source-inspection-plan.ts +34 -0
- package/packages/piagent-core/runtime/inspection/source-mutation-projection.ts +164 -0
- package/packages/piagent-core/runtime/inspection/source-mutation-store.ts +168 -0
- package/packages/piagent-core/runtime/inspection/source-open-target.ts +38 -0
- package/packages/piagent-core/runtime/inspection/source-revert-projection.ts +147 -0
- package/packages/piagent-core/runtime/inspection/task-baseline-start-capture.ts +22 -0
- package/packages/piagent-core/runtime/inspection/task-compaction-history.ts +160 -0
- package/packages/piagent-core/runtime/inspection/task-control-journal.ts +131 -0
- package/packages/piagent-core/runtime/inspection/task-handoff-history.ts +95 -0
- package/packages/piagent-core/runtime/inspection/task-provenance-projection.ts +60 -0
- package/packages/piagent-core/runtime/inspection/task-recovery-timeline.ts +88 -0
- package/packages/piagent-core/runtime/inspection/task-run-index.ts +87 -0
- package/packages/piagent-core/runtime/inspection/task-source-projection.ts +401 -0
- package/packages/piagent-core/runtime/inspection/task-subagent-tree.ts +101 -0
- package/packages/piagent-core/runtime/inspection/text-diff.ts +60 -0
- package/packages/piagent-core/runtime/inspection/verifier-snapshot-contract.ts +114 -0
- package/packages/piagent-core/runtime/inspection/verifier-snapshot-store.ts +189 -0
- package/packages/piagent-core/runtime/inspection/webui-snapshot.ts +320 -0
- package/packages/piagent-core/runtime/inspection/workspace-file-reader.ts +132 -0
- package/packages/piagent-core/runtime/inspection/workspace-source-projection.ts +96 -0
- package/packages/piagent-core/runtime/inspection/zero-turn-conformance.ts +175 -0
- package/packages/piagent-core/runtime/orchestration/owned-work-budget.ts +68 -4
- package/packages/piagent-core/runtime/policy/source-index-transaction.ts +173 -0
- package/packages/piagent-core/runtime/policy/source-mutation-guard-binding.ts +42 -0
- package/packages/piagent-core/runtime/policy/source-mutation-guard.ts +184 -0
- package/packages/piagent-core/runtime/policy/source-worktree-transaction.ts +105 -0
- package/packages/piagent-core/runtime/product/activity-inspector-footer.ts +5 -3
- package/packages/piagent-core/runtime/product/activity-inspector.ts +85 -343
- package/packages/piagent-core/runtime/recovery/resume-state.ts +38 -1
- package/packages/piagent-core/runtime/registration/activity-inspector-command.ts +68 -14
- package/packages/piagent-core/runtime/registration/task-start-tool.ts +13 -14
- package/packages/piagent-core/runtime/session/model-authorship-state.ts +31 -3
- package/packages/piagent-core/runtime/session/runtime-state.ts +11 -1
- package/packages/piagent-webui/dist/client/assets/index-DjMntaK5.js +172 -0
- package/packages/piagent-webui/dist/client/assets/index-DwKCWbwd.css +1 -0
- package/packages/piagent-webui/dist/client/index.html +16 -0
- package/packages/piagent-webui/extension/attachment-store.ts +323 -0
- package/packages/piagent-webui/extension/held-message-queue.ts +311 -0
- package/packages/piagent-webui/extension/lifecycle-controller.ts +408 -0
- package/packages/piagent-webui/extension/lifecycle-event-adapter.ts +23 -0
- package/packages/piagent-webui/extension/piagent-webui.ts +470 -0
- package/packages/piagent-webui/extension/review-controller.ts +160 -0
- package/packages/piagent-webui/extension/same-session-bridge.ts +500 -0
- package/packages/piagent-webui/extension/session-options-controller.ts +281 -0
- package/packages/piagent-webui/extension/session-stream-adapter.ts +249 -0
- package/packages/piagent-webui/extension/source-mutation-controller.ts +215 -0
- package/packages/piagent-webui/extension/source-open-controller.ts +136 -0
- package/packages/piagent-webui/extension/source-revert-controller.ts +189 -0
- package/packages/piagent-webui/extension/terminal-session-adapter.ts +73 -0
- package/packages/piagent-webui/extension/vscode-handoff.ts +51 -0
- package/packages/piagent-webui/gateway/control-socket.ts +92 -0
- package/packages/piagent-webui/gateway/gateway-events.ts +60 -0
- package/packages/piagent-webui/gateway/gateway-protocol-service.ts +64 -0
- package/packages/piagent-webui/gateway/gateway-service.ts +215 -0
- package/packages/piagent-webui/gateway/gateway-session-stream.ts +110 -0
- package/packages/piagent-webui/gateway/mcp-auth-broker.ts +158 -0
- package/packages/piagent-webui/gateway/native-project-picker.ts +29 -0
- package/packages/piagent-webui/gateway/pi-host.ts +41 -0
- package/packages/piagent-webui/gateway/profile-state.ts +1 -0
- package/packages/piagent-webui/gateway/project-registry.ts +108 -0
- package/packages/piagent-webui/gateway/provider-auth-broker.ts +172 -0
- package/packages/piagent-webui/gateway/session-catalog.ts +128 -0
- package/packages/piagent-webui/gateway/session-command-controller.ts +237 -0
- package/packages/piagent-webui/gateway/session-command-store.ts +224 -0
- package/packages/piagent-webui/gateway/session-inspection-registry.ts +204 -0
- package/packages/piagent-webui/gateway/session-lease-store.ts +1 -0
- package/packages/piagent-webui/gateway/session-metadata-store.ts +152 -0
- package/packages/piagent-webui/gateway/session-runtime-supervisor.ts +485 -0
- package/packages/piagent-webui/ownership/gateway-runtime-context.ts +8 -0
- package/packages/piagent-webui/ownership/profile-state.ts +117 -0
- package/packages/piagent-webui/ownership/session-lease-store.ts +329 -0
- package/packages/piagent-webui/ownership/session-refs.ts +8 -0
- package/packages/piagent-webui/package.json +33 -0
- package/packages/piagent-webui/server/README.md +4 -0
- package/packages/piagent-webui/server/benchmark-release-monitor.ts +230 -0
- package/packages/piagent-webui/server/core-inspection-provider.ts +403 -0
- package/packages/piagent-webui/server/gateway-websocket.ts +143 -0
- package/packages/piagent-webui/server/http-security.ts +27 -0
- package/packages/piagent-webui/server/ipc-read-model-client.ts +89 -0
- package/packages/piagent-webui/server/loopback-server.ts +368 -0
- package/packages/piagent-webui/server/read-model-provider.ts +37 -0
- package/packages/piagent-webui/server/read-only-router.ts +105 -0
- package/packages/piagent-webui/server/session-auth.ts +88 -0
- package/packages/piagent-webui/server/sidecar-main.ts +86 -0
- package/packages/piagent-webui/server/sse-hub.ts +76 -0
- package/packages/piagent-webui/server/static-bundle.ts +40 -0
- package/packages/piagent-webui/server/transcript-projection.ts +110 -0
- package/schemas/mutation-provenance-record.schema.json +100 -0
- package/schemas/piagent-webui/approval-v1.schema.json +654 -0
- package/schemas/piagent-webui/attachment-v1.schema.json +267 -0
- package/schemas/piagent-webui/capabilities-v1.schema.json +729 -0
- package/schemas/piagent-webui/catalog-v1.json +240 -0
- package/schemas/piagent-webui/commit-summary-v1.schema.json +63 -0
- package/schemas/piagent-webui/common-v1.schema.json +479 -0
- package/schemas/piagent-webui/control-command-v1.schema.json +1780 -0
- package/schemas/piagent-webui/diff-v1.schema.json +826 -0
- package/schemas/piagent-webui/gateway-capabilities-v1.schema.json +136 -0
- package/schemas/piagent-webui/gateway-protocol-v1.schema.json +456 -0
- package/schemas/piagent-webui/handoff-history-v1.schema.json +92 -0
- package/schemas/piagent-webui/model-catalog-v1.schema.json +95 -0
- package/schemas/piagent-webui/queue-v1.schema.json +99 -0
- package/schemas/piagent-webui/recovery-history-v1.schema.json +144 -0
- package/schemas/piagent-webui/release-monitor-v1.schema.json +173 -0
- package/schemas/piagent-webui/review-state-v1.schema.json +206 -0
- package/schemas/piagent-webui/runtime-event-v2.schema.json +5206 -0
- package/schemas/piagent-webui/session-catalog-v1.schema.json +222 -0
- package/schemas/piagent-webui/session-command-v1.schema.json +390 -0
- package/schemas/piagent-webui/snapshot-v1.schema.json +2622 -0
- package/schemas/piagent-webui/source-change-v1.schema.json +763 -0
- package/schemas/piagent-webui/source-mutation-v1.schema.json +96 -0
- package/schemas/piagent-webui/source-revert-v1.schema.json +130 -0
- package/schemas/piagent-webui/subagent-tree-v1.schema.json +88 -0
- package/schemas/piagent-webui/task-index-v1.schema.json +74 -0
- package/schemas/piagent-webui/task-timeline-v1.schema.json +49 -0
- package/schemas/piagent-webui/transcript-v1.schema.json +243 -0
- package/schemas/task-baseline-manifest.schema.json +122 -0
- package/schemas/verifier-file-snapshot.schema.json +81 -0
- package/scripts/check-architecture.mjs +1 -0
- package/scripts/check-doc-languages.mjs +19 -2
- package/scripts/check-third-party-neutrality.mjs +43 -0
- package/scripts/install-global.sh +1 -1
- package/scripts/piagent-cli.mjs +17 -3
- package/scripts/piagent-dashboard.mjs +208 -0
- package/scripts/piagent-webui-launcher.mjs +121 -0
- package/scripts/typescript-loader.mjs +26 -1
- package/scripts/verify-local.sh +253 -0
- package/scripts/verify-release-identity.mjs +4 -1
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
3
|
+
|
|
4
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
|
|
6
|
+
import { redactSensitiveText } from "../../piagent-core/extensions/redaction-core.js";
|
|
7
|
+
import { webUiModelRef } from "../../piagent-core/runtime/inspection/webui-snapshot.ts";
|
|
8
|
+
import { controlActionDigest, type BridgeIdentity, type BridgeRevisions, type SameSessionPiBridge,
|
|
9
|
+
type SessionOptionMutationPermit } from "./same-session-bridge.ts";
|
|
10
|
+
|
|
11
|
+
export const WEBUI_SESSION_OPTION_ENTRY_TYPE = "piagent-webui-session-option-v1";
|
|
12
|
+
const REF = /^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/;
|
|
13
|
+
const PUBLIC_REF = /^[A-Za-z0-9][A-Za-z0-9._:@~-]{0,159}$/;
|
|
14
|
+
const REVISION = /^[A-Za-z0-9][A-Za-z0-9._:~-]{0,159}$/;
|
|
15
|
+
const DIGEST = /^sha256:[a-f0-9]{64}$/;
|
|
16
|
+
const IDEMPOTENCY = /^[A-Za-z0-9._~-]{32,128}$/;
|
|
17
|
+
const THINKING = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
|
|
18
|
+
type ThinkingLevel = typeof THINKING[number];
|
|
19
|
+
type SessionOptionAction = "session-options.set-model" | "session-options.set-thinking";
|
|
20
|
+
type ModelLike = { provider?: unknown; id?: unknown; name?: unknown; reasoning?: unknown; input?: unknown; thinkingLevelMap?: unknown;
|
|
21
|
+
contextWindow?: unknown; maxTokens?: unknown };
|
|
22
|
+
type Command = {
|
|
23
|
+
schemaVersion: 1; version: "piagent-webui-control-v1"; messageType: "command"; commandId: string; idempotencyKey: string;
|
|
24
|
+
requestedAt: string; expiresAt: string; capabilityScope: "control.sessionOptions"; action: SessionOptionAction; actionDigest: string;
|
|
25
|
+
identity: BridgeIdentity; expectedRevisions: BridgeRevisions & { workspacePreimage: null; indexPreimage: null; patchPreimage: null };
|
|
26
|
+
payload: { effectScopeAcknowledged: "session-and-user-default"; modelRef?: string; thinkingLevel?: ThinkingLevel };
|
|
27
|
+
};
|
|
28
|
+
export type SessionOptionReceipt = {
|
|
29
|
+
schemaVersion: 1; version: "piagent-webui-control-v1"; messageType: "receipt"; commandId: string; idempotencyKeyDigest: string;
|
|
30
|
+
action: SessionOptionAction; actionDigest: string; identity: BridgeIdentity; phase: "settled" | "rejected" | "uncertain";
|
|
31
|
+
resultCode: "changed" | "unchanged" | "effect-unknown" | "stale-revision" | "identity-mismatch" | "capability-unavailable"
|
|
32
|
+
| "replay" | "idempotency-payload-mismatch" | "expired" | "invalid-command" | "resync-required";
|
|
33
|
+
requestedAt: string; settledAt: string; observedRevisionsBefore: BridgeRevisions; observedRevisionsAfter: BridgeRevisions;
|
|
34
|
+
deduplicated: boolean; auditRef: null; settlementEvidenceRef: string | null;
|
|
35
|
+
error: { code: string; message: string; retryable: false } | null;
|
|
36
|
+
};
|
|
37
|
+
type CatalogModel = { modelRef: string; provider: string; modelId: string; displayName: string; reasoning: boolean;
|
|
38
|
+
inputCapabilities: Array<"text" | "image">; supportedThinkingLevels: ThinkingLevel[]; contextWindow: number; maxOutputTokens: number };
|
|
39
|
+
|
|
40
|
+
function sha(value: string): string { return `sha256:${createHash("sha256").update(value).digest("hex")}`; }
|
|
41
|
+
function canonical(value: unknown): string {
|
|
42
|
+
if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
|
|
43
|
+
if (value && typeof value === "object") return `{${Object.entries(value as Record<string, unknown>).sort(([a], [b]) => a.localeCompare(b))
|
|
44
|
+
.map(([key, item]) => `${JSON.stringify(key)}:${canonical(item)}`).join(",")}}`;
|
|
45
|
+
return JSON.stringify(value);
|
|
46
|
+
}
|
|
47
|
+
function same(left: unknown, right: unknown): boolean { return canonical(left) === canonical(right); }
|
|
48
|
+
function exactKeys(value: unknown, keys: string[]): boolean {
|
|
49
|
+
return Boolean(value && typeof value === "object" && !Array.isArray(value)
|
|
50
|
+
&& same(Object.keys(value as object).sort(), [...keys].sort()));
|
|
51
|
+
}
|
|
52
|
+
function timestamp(value: unknown): value is string {
|
|
53
|
+
if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value)) return false;
|
|
54
|
+
const parsed = Date.parse(value); return Number.isFinite(parsed) && new Date(parsed).toISOString() === value;
|
|
55
|
+
}
|
|
56
|
+
function copy<T>(value: T): T { return structuredClone(value); }
|
|
57
|
+
function validIdentity(value: unknown): value is BridgeIdentity {
|
|
58
|
+
if (!exactKeys(value, ["projectRef", "runtimeInstanceId", "sessionRef", "taskId", "taskRunId", "agentOperationId", "toolCallId"])) return false;
|
|
59
|
+
const identity = value as BridgeIdentity;
|
|
60
|
+
return [identity.projectRef, identity.runtimeInstanceId, identity.sessionRef].every((item) => typeof item === "string" && REF.test(item))
|
|
61
|
+
&& [identity.taskId, identity.taskRunId].every((item) => item === null || PUBLIC_REF.test(item))
|
|
62
|
+
&& (identity.taskRunId === null || identity.taskId !== null) && (identity.agentOperationId === null || REF.test(identity.agentOperationId))
|
|
63
|
+
&& identity.toolCallId === null;
|
|
64
|
+
}
|
|
65
|
+
function validRevisions(value: unknown): value is Command["expectedRevisions"] {
|
|
66
|
+
if (!exactKeys(value, ["runtimeRevision", "taskRevision", "controlRevision", "workspaceRevision", "indexRevision", "approvalRevision",
|
|
67
|
+
"sessionOptionRevision", "queueRevision", "workspacePreimage", "indexPreimage", "patchPreimage"])) return false;
|
|
68
|
+
const revisions = value as Command["expectedRevisions"];
|
|
69
|
+
return REVISION.test(revisions.runtimeRevision) && [revisions.taskRevision, revisions.controlRevision, revisions.workspaceRevision,
|
|
70
|
+
revisions.indexRevision, revisions.approvalRevision, revisions.sessionOptionRevision, revisions.queueRevision]
|
|
71
|
+
.every((item) => item === null || REVISION.test(item)) && revisions.workspacePreimage === null && revisions.indexPreimage === null
|
|
72
|
+
&& revisions.patchPreimage === null;
|
|
73
|
+
}
|
|
74
|
+
function safeName(value: unknown, fallback: string): string {
|
|
75
|
+
return redactSensitiveText(String(value ?? fallback)).text.replace(/[\u0000-\u001F\u007F]/g, " ").replace(/\s+/g, " ").trim().slice(0, 160) || fallback;
|
|
76
|
+
}
|
|
77
|
+
function safePublicId(value: unknown): string | null {
|
|
78
|
+
if (typeof value !== "string" || !PUBLIC_REF.test(value)) return null;
|
|
79
|
+
return redactSensitiveText(value).redacted ? null : value;
|
|
80
|
+
}
|
|
81
|
+
function positive(value: unknown): number | null {
|
|
82
|
+
return Number.isInteger(value) && Number(value) >= 1 && Number(value) <= 100_000_000 ? Number(value) : null;
|
|
83
|
+
}
|
|
84
|
+
function thinkingLevels(model: ModelLike): ThinkingLevel[] {
|
|
85
|
+
if (model.reasoning !== true) return ["off"];
|
|
86
|
+
const mapping = model.thinkingLevelMap && typeof model.thinkingLevelMap === "object" ? model.thinkingLevelMap as Record<string, unknown> : {};
|
|
87
|
+
const levels = THINKING.filter((level) => mapping[level] !== null && !(["xhigh", "max"].includes(level) && mapping[level] === undefined));
|
|
88
|
+
return levels.length ? [...levels] : ["off"];
|
|
89
|
+
}
|
|
90
|
+
function catalogModel(value: ModelLike): CatalogModel | null {
|
|
91
|
+
const provider = safePublicId(value.provider), modelId = safePublicId(value.id);
|
|
92
|
+
const contextWindow = positive(value.contextWindow), maxOutputTokens = positive(value.maxTokens);
|
|
93
|
+
if (!provider || !modelId || typeof value.reasoning !== "boolean" || !contextWindow || !maxOutputTokens) return null;
|
|
94
|
+
const inputCapabilities = Array.isArray(value.input) ? [...new Set(value.input.filter((item): item is "text" | "image" => item === "text" || item === "image"))] : [];
|
|
95
|
+
return { modelRef: webUiModelRef(provider, modelId), provider, modelId, displayName: safeName(value.name, modelId), reasoning: value.reasoning,
|
|
96
|
+
inputCapabilities, supportedThinkingLevels: thinkingLevels(value), contextWindow, maxOutputTokens };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export class SessionOptionsController {
|
|
100
|
+
readonly #pi: ExtensionAPI;
|
|
101
|
+
readonly #bridge: SameSessionPiBridge;
|
|
102
|
+
readonly #now: () => Date;
|
|
103
|
+
#ctx: ExtensionContext | null = null;
|
|
104
|
+
#models = new Map<string, ModelLike>();
|
|
105
|
+
#receiptsByKey = new Map<string, SessionOptionReceipt>();
|
|
106
|
+
#receiptsByCommand = new Map<string, SessionOptionReceipt>();
|
|
107
|
+
#serial: Promise<unknown> = Promise.resolve();
|
|
108
|
+
readonly #hostMutation = new AsyncLocalStorage<symbol>();
|
|
109
|
+
#activeHostMutation: symbol | null = null;
|
|
110
|
+
|
|
111
|
+
constructor(options: { pi: ExtensionAPI; bridge: SameSessionPiBridge; now?: () => Date }) {
|
|
112
|
+
this.#pi = options.pi; this.#bridge = options.bridge; this.#now = options.now ?? (() => new Date());
|
|
113
|
+
}
|
|
114
|
+
bind(ctx: ExtensionContext): void { this.#ctx = ctx; this.#models.clear(); this.#receiptsByKey.clear(); this.#receiptsByCommand.clear(); }
|
|
115
|
+
refresh(ctx: ExtensionContext): void { if (this.#bridge.refresh(ctx)) this.#ctx = ctx; }
|
|
116
|
+
observeHostOptionChange(ctx: ExtensionContext): void {
|
|
117
|
+
const causal = this.#activeHostMutation !== null && this.#hostMutation.getStore() === this.#activeHostMutation;
|
|
118
|
+
this.#bridge.observeSessionOptionChange(ctx, causal); this.refresh(ctx);
|
|
119
|
+
}
|
|
120
|
+
reset(): void { this.#ctx = null; this.#models.clear(); this.#receiptsByKey.clear(); this.#receiptsByCommand.clear(); }
|
|
121
|
+
|
|
122
|
+
catalog(): Record<string, unknown> {
|
|
123
|
+
const snapshot = this.#bridge.snapshot();
|
|
124
|
+
if (!this.#ctx || snapshot.state !== "ready" || !snapshot.identity || !snapshot.revisions) throw new Error("webui-session-options-binding-unavailable");
|
|
125
|
+
const values = this.#availableModels(this.#ctx), projected: CatalogModel[] = []; this.#models.clear();
|
|
126
|
+
for (const value of values.slice(0, 300)) {
|
|
127
|
+
const model = catalogModel(value); if (!model || this.#models.has(model.modelRef)) continue;
|
|
128
|
+
this.#models.set(model.modelRef, value); projected.push(model);
|
|
129
|
+
}
|
|
130
|
+
projected.sort((a, b) => `${a.provider}/${a.modelId}`.localeCompare(`${b.provider}/${b.modelId}`));
|
|
131
|
+
const active = catalogModel(this.#ctx.model as ModelLike), thinking = this.#currentThinking();
|
|
132
|
+
const ready = Boolean(active && this.#models.has(active.modelRef) && THINKING.includes(thinking as ThinkingLevel) && projected.length);
|
|
133
|
+
return { schemaVersion: 1, version: "piagent-webui-model-catalog-v1", generatedAt: this.#now().toISOString(), identity: snapshot.identity,
|
|
134
|
+
revision: snapshot.revisions, state: ready ? "ready" : "unavailable",
|
|
135
|
+
catalogScope: ready ? (this.#ctx.scopedModels.length ? "session-scoped" : "authenticated-all") : "unavailable",
|
|
136
|
+
effectScope: "session-and-user-default", activeModelRef: ready ? active!.modelRef : null, activeThinkingLevel: ready ? thinking : null,
|
|
137
|
+
models: ready ? projected : [], reasonCode: ready ? null : "authenticated-model-catalog-unavailable" };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
execute(input: unknown): Promise<SessionOptionReceipt> {
|
|
141
|
+
const run = this.#serial.then(() => this.#execute(input), () => this.#execute(input)); this.#serial = run.catch(() => undefined); return run;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async #execute(input: unknown): Promise<SessionOptionReceipt> {
|
|
145
|
+
const command = input as Command, snapshot = this.#bridge.snapshot(), structural = this.#validate(command);
|
|
146
|
+
if (!this.#ctx || snapshot.state !== "ready" || !snapshot.identity || !snapshot.revisions)
|
|
147
|
+
return this.#reject(command, "resync-required", "session-options-binding-not-ready", "The current Pi session option binding is unavailable.");
|
|
148
|
+
if (structural) return this.#reject(command, "invalid-command", structural, "The session option command is invalid.");
|
|
149
|
+
const keyDigest = sha(command.idempotencyKey), old = this.#receiptsByKey.get(keyDigest) ?? this.#receiptsByCommand.get(command.commandId);
|
|
150
|
+
if (old) {
|
|
151
|
+
if (old.commandId !== command.commandId || old.actionDigest !== command.actionDigest || old.idempotencyKeyDigest !== keyDigest)
|
|
152
|
+
return this.#reject(command, "idempotency-payload-mismatch", "idempotency-payload-mismatch", "The command key is bound to another option change.");
|
|
153
|
+
return { ...copy(old), deduplicated: true };
|
|
154
|
+
}
|
|
155
|
+
const now = this.#now().getTime();
|
|
156
|
+
if (Date.parse(command.requestedAt) > now + 30_000) return this.#reject(command, "invalid-command", "requested-at-in-future", "The command timestamp is not yet valid.");
|
|
157
|
+
if (now > Date.parse(command.expiresAt)) return this.#reject(command, "expired", "command-expired", "The command expired before execution.");
|
|
158
|
+
if (!same(command.identity, snapshot.identity)) return this.#reject(command, "identity-mismatch", "identity-mismatch", "The command targets another Pi session.");
|
|
159
|
+
if (!["runtimeRevision", "taskRevision", "controlRevision", "sessionOptionRevision"].every((key) =>
|
|
160
|
+
(command.expectedRevisions as any)[key] === (snapshot.revisions as any)[key]))
|
|
161
|
+
return this.#reject(command, "stale-revision", "stale-revision", "The Pi session option state changed before execution.");
|
|
162
|
+
if (snapshot.liveness !== "idle" || !this.#ctx.isIdle() || snapshot.identity.agentOperationId)
|
|
163
|
+
return this.#reject(command, "capability-unavailable", "agent-not-idle", "Model and thinking can change only while Pi is idle.");
|
|
164
|
+
this.catalog();
|
|
165
|
+
const permit = this.#bridge.beginSessionOptionMutation(), ctx = this.#ctx;
|
|
166
|
+
if (!permit) return this.#reject(command, "capability-unavailable", "session-option-linearization-unavailable", "Pi is no longer at an idle option-change boundary.");
|
|
167
|
+
try { return command.action === "session-options.set-model" ? await this.#setModel(command, ctx, permit) : this.#setThinking(command, ctx, permit); }
|
|
168
|
+
finally { permit.release(); }
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async #setModel(command: Command, ctx: ExtensionContext, permit: SessionOptionMutationPermit): Promise<SessionOptionReceipt> {
|
|
172
|
+
const model = this.#models.get(command.payload.modelRef!);
|
|
173
|
+
if (!model) return this.#reject(command, "capability-unavailable", "model-not-selectable", "The selected model is not in the authenticated Pi catalog.");
|
|
174
|
+
const beforeRef = catalogModel(ctx.model as ModelLike)?.modelRef ?? null;
|
|
175
|
+
let result: "changed" | "unchanged" | "effect-unknown" = beforeRef === command.payload.modelRef ? "unchanged" : "changed";
|
|
176
|
+
if (result === "changed") {
|
|
177
|
+
const token = Symbol("webui-session-option"); this.#activeHostMutation = token;
|
|
178
|
+
try {
|
|
179
|
+
const accepted = await this.#hostMutation.run(token, () => this.#pi.setModel(model as any));
|
|
180
|
+
const actual = catalogModel(ctx.model as ModelLike)?.modelRef ?? null;
|
|
181
|
+
if (!accepted || actual !== command.payload.modelRef) result = "effect-unknown";
|
|
182
|
+
} catch { result = "effect-unknown"; } finally { this.#activeHostMutation = null; }
|
|
183
|
+
}
|
|
184
|
+
return this.#settle(command, result, permit);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
#setThinking(command: Command, ctx: ExtensionContext, permit: SessionOptionMutationPermit): SessionOptionReceipt {
|
|
188
|
+
const target = command.payload.thinkingLevel!, active = catalogModel(ctx.model as ModelLike);
|
|
189
|
+
if (!active?.supportedThinkingLevels.includes(target))
|
|
190
|
+
return this.#reject(command, "capability-unavailable", "thinking-level-not-supported", "The active model does not support this thinking level.");
|
|
191
|
+
const before = this.#thinkingFor(ctx); let result: "changed" | "unchanged" | "effect-unknown" = before === target ? "unchanged" : "changed";
|
|
192
|
+
if (result === "changed") {
|
|
193
|
+
const token = Symbol("webui-session-option"); this.#activeHostMutation = token;
|
|
194
|
+
try { this.#hostMutation.run(token, () => this.#pi.setThinkingLevel(target as any)); if (this.#thinkingFor(ctx) !== target) result = "effect-unknown"; }
|
|
195
|
+
catch { result = "effect-unknown"; } finally { this.#activeHostMutation = null; }
|
|
196
|
+
}
|
|
197
|
+
return this.#settle(command, result, permit);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
#settle(command: Command, result: "changed" | "unchanged" | "effect-unknown", permit: SessionOptionMutationPermit): SessionOptionReceipt {
|
|
201
|
+
const evidenceRef = `session-option-evidence.${randomBytes(24).toString("hex")}`; let receipt: SessionOptionReceipt | null = null;
|
|
202
|
+
const observation = permit.commitObservation((before, after) => {
|
|
203
|
+
receipt = this.#receipt(command, before, after, result === "effect-unknown" ? "uncertain" : "settled", result,
|
|
204
|
+
result === "effect-unknown" ? { code: "session-option-effect-unconfirmed", message: "Pi did not expose the requested active setting after the change.", retryable: false } : null,
|
|
205
|
+
result === "effect-unknown" ? null : evidenceRef);
|
|
206
|
+
this.#pi.appendEntry(WEBUI_SESSION_OPTION_ENTRY_TYPE, { schemaVersion: 1, evidenceRef, action: command.action,
|
|
207
|
+
targetRef: command.action === "session-options.set-model" ? command.payload.modelRef : command.payload.thinkingLevel,
|
|
208
|
+
resultCode: result, sessionOptionRevision: after.sessionOptionRevision });
|
|
209
|
+
});
|
|
210
|
+
if (!observation) {
|
|
211
|
+
const before = this.#domainRevisions(command.expectedRevisions), after = this.#bridge.snapshot().revisions ?? before;
|
|
212
|
+
return this.#receipt(command, before, after, "uncertain", "effect-unknown",
|
|
213
|
+
{ code: "session-option-binding-lost", message: "The session binding changed while the setting was being applied.", retryable: false }, null);
|
|
214
|
+
}
|
|
215
|
+
if (!receipt) return this.#receipt(command, observation.before, observation.after, "uncertain", "effect-unknown",
|
|
216
|
+
{ code: "session-option-concurrent-selection", message: "A native Pi selection raced this WebUI setting change.", retryable: false }, null);
|
|
217
|
+
if (!observation.recorded) receipt = this.#receipt(command, observation.before, observation.after, "uncertain", "effect-unknown",
|
|
218
|
+
{ code: "session-option-evidence-unavailable", message: "The setting may have changed, but its local evidence could not be recorded.", retryable: false }, null);
|
|
219
|
+
return this.#remember(receipt);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
#validate(command: Command): string | null {
|
|
223
|
+
if (!command || typeof command !== "object" || command.schemaVersion !== 1 || command.version !== "piagent-webui-control-v1"
|
|
224
|
+
|| command.messageType !== "command" || command.capabilityScope !== "control.sessionOptions"
|
|
225
|
+
|| !["session-options.set-model", "session-options.set-thinking"].includes(command.action)) return "unsupported-command-shape";
|
|
226
|
+
if (!exactKeys(command, ["schemaVersion", "version", "messageType", "commandId", "idempotencyKey", "requestedAt", "expiresAt", "capabilityScope",
|
|
227
|
+
"action", "actionDigest", "identity", "expectedRevisions", "payload"]) || !validIdentity(command.identity) || !validRevisions(command.expectedRevisions)
|
|
228
|
+
|| !REF.test(command.commandId) || !IDEMPOTENCY.test(command.idempotencyKey) || !timestamp(command.requestedAt) || !timestamp(command.expiresAt)
|
|
229
|
+
|| !REVISION.test(command.expectedRevisions.sessionOptionRevision ?? "")
|
|
230
|
+
|| Date.parse(command.requestedAt) > Date.parse(command.expiresAt) || Date.parse(command.expiresAt) - Date.parse(command.requestedAt) > 300_000)
|
|
231
|
+
return "invalid-command-metadata";
|
|
232
|
+
const expectedPayload = command.action === "session-options.set-model" ? ["modelRef", "effectScopeAcknowledged"] : ["thinkingLevel", "effectScopeAcknowledged"];
|
|
233
|
+
if (!exactKeys(command.payload, expectedPayload) || command.payload.effectScopeAcknowledged !== "session-and-user-default") return "effect-scope-not-acknowledged";
|
|
234
|
+
if (command.action === "session-options.set-model" && (typeof command.payload.modelRef !== "string" || !REF.test(command.payload.modelRef))) return "invalid-model-ref";
|
|
235
|
+
if (command.action === "session-options.set-thinking" && !THINKING.includes(command.payload.thinkingLevel as ThinkingLevel)) return "invalid-thinking-level";
|
|
236
|
+
if (!DIGEST.test(command.actionDigest) || command.actionDigest !== controlActionDigest(command)) return "action-digest-mismatch";
|
|
237
|
+
return null;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
#receipt(command: Command, before: BridgeRevisions, after: BridgeRevisions, phase: "settled" | "uncertain",
|
|
241
|
+
resultCode: "changed" | "unchanged" | "effect-unknown", error: SessionOptionReceipt["error"], evidence: string | null): SessionOptionReceipt {
|
|
242
|
+
return { schemaVersion: 1, version: "piagent-webui-control-v1", messageType: "receipt", commandId: command.commandId,
|
|
243
|
+
idempotencyKeyDigest: sha(command.idempotencyKey), action: command.action, actionDigest: command.actionDigest, identity: copy(command.identity),
|
|
244
|
+
phase, resultCode, requestedAt: command.requestedAt, settledAt: this.#now().toISOString(), observedRevisionsBefore: copy(before),
|
|
245
|
+
observedRevisionsAfter: copy(after), deduplicated: false, auditRef: null, settlementEvidenceRef: evidence, error };
|
|
246
|
+
}
|
|
247
|
+
#reject(command: Command, resultCode: SessionOptionReceipt["resultCode"], code: string, message: string): SessionOptionReceipt {
|
|
248
|
+
const snapshot = this.#bridge.snapshot(), identity = validIdentity(command?.identity) ? command.identity : snapshot.identity ?? {
|
|
249
|
+
projectRef: "project.unavailable", runtimeInstanceId: "runtime.unavailable", sessionRef: "session.unavailable", taskId: null, taskRunId: null,
|
|
250
|
+
agentOperationId: null, toolCallId: null };
|
|
251
|
+
const revisions = snapshot.revisions ?? { runtimeRevision: "runtime-rev.unavailable", taskRevision: null, controlRevision: null,
|
|
252
|
+
workspaceRevision: null, indexRevision: null, approvalRevision: null, sessionOptionRevision: null, queueRevision: null };
|
|
253
|
+
const action = ["session-options.set-model", "session-options.set-thinking"].includes(command?.action) ? command.action : "session-options.set-model";
|
|
254
|
+
return { schemaVersion: 1, version: "piagent-webui-control-v1", messageType: "receipt", commandId: REF.test(command?.commandId ?? "") ? command.commandId : "command.invalid",
|
|
255
|
+
idempotencyKeyDigest: IDEMPOTENCY.test(command?.idempotencyKey ?? "") ? sha(command.idempotencyKey) : sha("invalid-idempotency"), action,
|
|
256
|
+
actionDigest: DIGEST.test(command?.actionDigest ?? "") ? command.actionDigest : sha(code), identity: copy(identity), phase: "rejected", resultCode,
|
|
257
|
+
requestedAt: timestamp(command?.requestedAt) ? command.requestedAt : this.#now().toISOString(), settledAt: this.#now().toISOString(),
|
|
258
|
+
observedRevisionsBefore: copy(revisions), observedRevisionsAfter: copy(revisions), deduplicated: resultCode === "replay", auditRef: null,
|
|
259
|
+
settlementEvidenceRef: null, error: { code, message, retryable: false } };
|
|
260
|
+
}
|
|
261
|
+
#remember(receipt: SessionOptionReceipt): SessionOptionReceipt {
|
|
262
|
+
this.#receiptsByKey.set(receipt.idempotencyKeyDigest, copy(receipt)); this.#receiptsByCommand.set(receipt.commandId, copy(receipt)); return receipt;
|
|
263
|
+
}
|
|
264
|
+
#domainRevisions(value: BridgeRevisions): BridgeRevisions {
|
|
265
|
+
return { runtimeRevision: value.runtimeRevision, taskRevision: value.taskRevision, controlRevision: value.controlRevision,
|
|
266
|
+
workspaceRevision: value.workspaceRevision, indexRevision: value.indexRevision, approvalRevision: value.approvalRevision,
|
|
267
|
+
sessionOptionRevision: value.sessionOptionRevision, queueRevision: value.queueRevision };
|
|
268
|
+
}
|
|
269
|
+
#currentThinking(): ThinkingLevel | null {
|
|
270
|
+
return this.#ctx ? this.#thinkingFor(this.#ctx) : null;
|
|
271
|
+
}
|
|
272
|
+
#thinkingFor(ctx: ExtensionContext): ThinkingLevel | null {
|
|
273
|
+
const value = ctx.thinkingLevel ?? this.#pi.getThinkingLevel(); return THINKING.includes(value as ThinkingLevel) ? value as ThinkingLevel : null;
|
|
274
|
+
}
|
|
275
|
+
#availableModels(ctx: ExtensionContext): ModelLike[] {
|
|
276
|
+
const available = ctx.modelRegistry.getAvailable() as ModelLike[];
|
|
277
|
+
if (!ctx.scopedModels.length) return available;
|
|
278
|
+
const scope = new Set(ctx.scopedModels.map((item: any) => `${item.model?.provider}\0${item.model?.id}`));
|
|
279
|
+
return available.filter((item) => scope.has(`${item.provider}\0${item.id}`));
|
|
280
|
+
}
|
|
281
|
+
}
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
import { redactSensitiveText } from "../../piagent-core/extensions/redaction-core.js";
|
|
4
|
+
import type { RuntimeEventDraft, RuntimeEventRevision } from "../../piagent-core/runtime/inspection/runtime-event-store.ts";
|
|
5
|
+
import type { BridgeIdentity, BridgeSnapshot } from "./same-session-bridge.ts";
|
|
6
|
+
|
|
7
|
+
const MAX_STREAM_BUFFER = 65_536;
|
|
8
|
+
const MAX_DELTA = 16_384;
|
|
9
|
+
const MAX_MESSAGE_STREAM_EVENTS = 128;
|
|
10
|
+
const STREAM_FLUSH_CHARS = 1_024;
|
|
11
|
+
const STREAM_FLUSH_INTERVAL_MS = 100;
|
|
12
|
+
const ANSI = /\u001b(?:[@-_]|\[[0-?]*[ -/]*[@-~])/g;
|
|
13
|
+
const PRIVATE_KEY_BEGIN = /-----BEGIN [A-Z ]*PRIVATE KEY-----/;
|
|
14
|
+
const PRIVATE_KEY_END = /-----END [A-Z ]*PRIVATE KEY-----/;
|
|
15
|
+
|
|
16
|
+
type MessageRole = "user" | "assistant" | "tool-result";
|
|
17
|
+
type ActiveMessage = { ref: string; role: MessageRole; rawBuffer: string; chunkSequence: number; truncated: boolean;
|
|
18
|
+
emittedEvents: number; lastFlushAt: number; thinking: Set<number>; thinkingStreaming: Set<number>; thinkingCompleted: Set<number> };
|
|
19
|
+
|
|
20
|
+
function hash(value: string): string { return createHash("sha256").update(value).digest("hex"); }
|
|
21
|
+
function opaque(prefix: string, value: unknown): string { return `${prefix}.${hash(JSON.stringify(value))}`; }
|
|
22
|
+
function digest(value: string): string { return `sha256:${hash(value)}`; }
|
|
23
|
+
function controls(value: string): string {
|
|
24
|
+
return value.replace(ANSI, "").replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, " ");
|
|
25
|
+
}
|
|
26
|
+
function safe(value: unknown, maximum = 4_000): { text: string; redacted: boolean; truncated: boolean } {
|
|
27
|
+
const source = controls(String(value ?? "")), begin = source.search(PRIVATE_KEY_BEGIN);
|
|
28
|
+
const incompleteKey = begin >= 0 && !PRIVATE_KEY_END.test(source.slice(begin));
|
|
29
|
+
const protectedSource = incompleteKey ? `${source.slice(0, begin)}[REDACTED_SECRET]` : source;
|
|
30
|
+
const projected = redactSensitiveText(protectedSource);
|
|
31
|
+
return { text: projected.text.slice(0, maximum), redacted: incompleteKey || projected.redacted, truncated: projected.text.length > maximum };
|
|
32
|
+
}
|
|
33
|
+
function safeToolName(value: unknown): string {
|
|
34
|
+
const projected = safe(value, 128);
|
|
35
|
+
if (projected.redacted) return "redacted-tool";
|
|
36
|
+
return projected.text.replace(/[^A-Za-z0-9._:-]/g, "-").replace(/^[^A-Za-z0-9]+/, "").slice(0, 128) || "tool";
|
|
37
|
+
}
|
|
38
|
+
function role(message: any): MessageRole | null {
|
|
39
|
+
return message?.role === "user" ? "user" : message?.role === "assistant" ? "assistant" : message?.role === "toolResult" ? "tool-result" : null;
|
|
40
|
+
}
|
|
41
|
+
function text(message: any): string {
|
|
42
|
+
if (typeof message?.content === "string") return message.content;
|
|
43
|
+
return Array.isArray(message?.content) ? message.content.filter((item: any) => item?.type === "text" && typeof item.text === "string")
|
|
44
|
+
.map((item: any) => item.text).join("\n") : "";
|
|
45
|
+
}
|
|
46
|
+
function imageCount(message: any): number {
|
|
47
|
+
return Array.isArray(message?.content) ? Math.min(32, message.content.filter((item: any) => item?.type === "image").length) : 0;
|
|
48
|
+
}
|
|
49
|
+
function stopReason(message: any): "pending" | "stop" | "length" | "toolUse" | "error" | "aborted" | "deferred" | null {
|
|
50
|
+
return ["pending", "stop", "length", "toolUse", "error", "aborted", "deferred"].includes(message?.stopReason) ? message.stopReason : null;
|
|
51
|
+
}
|
|
52
|
+
function usage(message: any) {
|
|
53
|
+
const value = message?.usage;
|
|
54
|
+
if (!value || typeof value !== "object") return null;
|
|
55
|
+
const count = (candidate: unknown): number | null => typeof candidate === "number" && Number.isFinite(candidate) && candidate >= 0
|
|
56
|
+
? Math.min(1_000_000_000_000, Math.floor(candidate)) : null;
|
|
57
|
+
return { input: count(value.input), output: count(value.output), cacheRead: count(value.cacheRead), cacheWrite: count(value.cacheWrite),
|
|
58
|
+
reasoning: count(value.reasoning), total: count(value.totalTokens ?? value.total) };
|
|
59
|
+
}
|
|
60
|
+
function timestamp(value: unknown, now: Date): string {
|
|
61
|
+
const parsed = typeof value === "number" && Number.isFinite(value) ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
|
|
62
|
+
return Number.isFinite(parsed) && parsed <= now.getTime() ? new Date(parsed).toISOString() : now.toISOString();
|
|
63
|
+
}
|
|
64
|
+
function correlation() {
|
|
65
|
+
return { commandId: null, messageRequestId: null, replacementId: null, approvalRequestId: null, causationEventId: null, idempotencyKeyDigest: null };
|
|
66
|
+
}
|
|
67
|
+
function redaction(applied = false, truncated = false) { return { applied, valuesRemoved: applied ? 1 : 0, truncated }; }
|
|
68
|
+
function identityReady(identity: BridgeIdentity | null): identity is BridgeIdentity & { agentOperationId: string } {
|
|
69
|
+
return Boolean(identity?.agentOperationId);
|
|
70
|
+
}
|
|
71
|
+
function activityPayload(state: "started" | "progress" | "finished" | "failed", activityRef: string, toolName: string) {
|
|
72
|
+
return { state, activityType: "tool", activityRef, toolName, inputDigest: null, outputDigest: null, preview: null, previewKind: "none",
|
|
73
|
+
outputBytes: null, outputLines: null, exitCode: null, isError: state === "finished" ? false : state === "failed" ? true : null,
|
|
74
|
+
affectedFileRefs: [], criterionIds: [], verifierAttemptIds: [], reasonCode: state === "failed" ? "tool-execution-failed" : null };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export class PiSessionStreamAdapter {
|
|
78
|
+
readonly #now: () => Date;
|
|
79
|
+
#turnIndex: number | null = null;
|
|
80
|
+
#messageCounter = 0;
|
|
81
|
+
#activeByRole = new Map<MessageRole, ActiveMessage>();
|
|
82
|
+
#lastMessageRef: string | null = null;
|
|
83
|
+
#toolRefs = new Map<string, string>();
|
|
84
|
+
#lastToolProgress = new Map<string, number>();
|
|
85
|
+
|
|
86
|
+
constructor(options: { now?: () => Date } = {}) { this.#now = options.now ?? (() => new Date()); }
|
|
87
|
+
reset(): void {
|
|
88
|
+
this.#turnIndex = null; this.#messageCounter = 0; this.#activeByRole.clear(); this.#lastMessageRef = null;
|
|
89
|
+
this.#toolRefs.clear(); this.#lastToolProgress.clear();
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
#base(snapshot: BridgeSnapshot, sourceObservedAt?: unknown): Omit<RuntimeEventDraft, "kind" | "payload" | "evidence" | "redaction"> | null {
|
|
93
|
+
if (!snapshot.revisions || !identityReady(snapshot.identity)) return null;
|
|
94
|
+
const now = this.#now(), identity = snapshot.identity;
|
|
95
|
+
return { sourceObservedAt: timestamp(sourceObservedAt, now), projectRef: identity.projectRef, runtimeInstanceId: identity.runtimeInstanceId,
|
|
96
|
+
sessionRef: identity.sessionRef, taskId: identity.taskId, taskRunId: identity.taskRunId, agentOperationId: identity.agentOperationId,
|
|
97
|
+
turnIndex: this.#turnIndex, messageRef: null, toolCallId: null, revision: structuredClone(snapshot.revisions) as RuntimeEventRevision, correlation: correlation() };
|
|
98
|
+
}
|
|
99
|
+
#draft(snapshot: BridgeSnapshot, kind: string, payload: Record<string, unknown>, options: { sourceObservedAt?: unknown; messageRef?: string;
|
|
100
|
+
toolCallId?: string; redacted?: boolean; truncated?: boolean; evidence?: "observed" | "derived" } = {}): RuntimeEventDraft | null {
|
|
101
|
+
const base = this.#base(snapshot, options.sourceObservedAt); if (!base) return null;
|
|
102
|
+
return { ...base, messageRef: options.messageRef ?? null, toolCallId: options.toolCallId ?? null, kind,
|
|
103
|
+
evidence: options.evidence ?? "observed", payload, redaction: redaction(options.redacted, options.truncated) };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
agentStarted(snapshot: BridgeSnapshot): RuntimeEventDraft[] {
|
|
107
|
+
const draft = this.#draft(snapshot, "agent-operation.started", { dispatchSource: "unknown", delivery: "unknown", inputDigest: null });
|
|
108
|
+
return draft ? [draft] : [];
|
|
109
|
+
}
|
|
110
|
+
turnStarted(event: { turnIndex?: unknown; timestamp?: unknown }, snapshot: BridgeSnapshot): RuntimeEventDraft[] {
|
|
111
|
+
if (!Number.isInteger(event.turnIndex) || Number(event.turnIndex) < 0 || Number(event.turnIndex) > 1_000_000_000) return [];
|
|
112
|
+
this.#turnIndex = Number(event.turnIndex); this.#activeByRole.clear(); this.#lastMessageRef = null;
|
|
113
|
+
const draft = this.#draft(snapshot, "turn.started", { phase: "started" }, { sourceObservedAt: event.timestamp });
|
|
114
|
+
return draft ? [draft] : [];
|
|
115
|
+
}
|
|
116
|
+
messageStarted(event: { message?: unknown }, snapshot: BridgeSnapshot): RuntimeEventDraft[] {
|
|
117
|
+
const message = event.message as any, messageRole = role(message); if (!messageRole || this.#turnIndex === null) return [];
|
|
118
|
+
const base = this.#base(snapshot, message?.timestamp); if (!base) return [];
|
|
119
|
+
const messageRef = opaque("message", [base.sessionRef, base.agentOperationId, this.#turnIndex, ++this.#messageCounter, messageRole]);
|
|
120
|
+
const source = messageRole === "tool-result" ? "" : safe(text(message), MAX_STREAM_BUFFER).text;
|
|
121
|
+
this.#activeByRole.set(messageRole, { ref: messageRef, role: messageRole, rawBuffer: "", chunkSequence: 0, truncated: false,
|
|
122
|
+
emittedEvents: 0, lastFlushAt: this.#now().getTime(),
|
|
123
|
+
thinking: new Set(), thinkingStreaming: new Set(), thinkingCompleted: new Set() });
|
|
124
|
+
this.#lastMessageRef = messageRef;
|
|
125
|
+
const draft = this.#draft(snapshot, "message.started", { role: messageRole, contentDigest: source ? digest(source) : null,
|
|
126
|
+
textChars: source ? source.length : null, imageCount: imageCount(message) }, { sourceObservedAt: message?.timestamp, messageRef });
|
|
127
|
+
return draft ? [draft] : [];
|
|
128
|
+
}
|
|
129
|
+
#deltaDrafts(snapshot: BridgeSnapshot, active: ActiveMessage, value: string, redactedValue: boolean, truncatedValue = false): RuntimeEventDraft[] {
|
|
130
|
+
const result: RuntimeEventDraft[] = [];
|
|
131
|
+
for (let offset = 0; offset < value.length; offset += MAX_DELTA) {
|
|
132
|
+
if (active.emittedEvents >= MAX_MESSAGE_STREAM_EVENTS) { active.truncated = true; break; }
|
|
133
|
+
const delta = value.slice(offset, offset + MAX_DELTA);
|
|
134
|
+
const draft = this.#draft(snapshot, "message.text-delta", { role: "assistant", contentIndex: 0,
|
|
135
|
+
chunkSequence: active.chunkSequence++, delta, deltaDigest: digest(delta) },
|
|
136
|
+
{ messageRef: active.ref, redacted: redactedValue, truncated: truncatedValue });
|
|
137
|
+
if (draft) { result.push(draft); active.emittedEvents += 1; }
|
|
138
|
+
}
|
|
139
|
+
return result;
|
|
140
|
+
}
|
|
141
|
+
#drainLines(snapshot: BridgeSnapshot, active: ActiveMessage, final: boolean): RuntimeEventDraft[] {
|
|
142
|
+
let take = final ? active.rawBuffer.length : active.rawBuffer.lastIndexOf("\n") + 1;
|
|
143
|
+
if (take <= 0) return [];
|
|
144
|
+
const candidate = active.rawBuffer.slice(0, take), privateStart = candidate.search(PRIVATE_KEY_BEGIN);
|
|
145
|
+
if (privateStart >= 0 && !PRIVATE_KEY_END.test(candidate.slice(privateStart))) {
|
|
146
|
+
if (!final) take = privateStart;
|
|
147
|
+
else {
|
|
148
|
+
active.rawBuffer = "";
|
|
149
|
+
const before = redactSensitiveText(controls(candidate.slice(0, privateStart)));
|
|
150
|
+
return this.#deltaDrafts(snapshot, active, `${before.text}[REDACTED_SECRET]`, true, active.truncated);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
if (take <= 0) return [];
|
|
154
|
+
const source = active.rawBuffer.slice(0, take); active.rawBuffer = active.rawBuffer.slice(take);
|
|
155
|
+
const projected = redactSensitiveText(controls(source));
|
|
156
|
+
return this.#deltaDrafts(snapshot, active, projected.text, projected.redacted, active.truncated);
|
|
157
|
+
}
|
|
158
|
+
messageUpdated(event: { assistantMessageEvent?: any }, snapshot: BridgeSnapshot): RuntimeEventDraft[] {
|
|
159
|
+
const update = event.assistantMessageEvent, active = this.#activeByRole.get("assistant"); if (!active || !update) return [];
|
|
160
|
+
if (update.type === "text_delta" && typeof update.delta === "string") {
|
|
161
|
+
if (active.emittedEvents >= MAX_MESSAGE_STREAM_EVENTS) { active.truncated = true; return []; }
|
|
162
|
+
const remaining = MAX_STREAM_BUFFER - active.rawBuffer.length;
|
|
163
|
+
if (remaining <= 0) { active.truncated = true; return []; }
|
|
164
|
+
active.rawBuffer += update.delta.slice(0, remaining); if (update.delta.length > remaining) active.truncated = true;
|
|
165
|
+
const now = this.#now().getTime();
|
|
166
|
+
if (active.rawBuffer.length < STREAM_FLUSH_CHARS && now - active.lastFlushAt < STREAM_FLUSH_INTERVAL_MS
|
|
167
|
+
&& !PRIVATE_KEY_END.test(active.rawBuffer)) return [];
|
|
168
|
+
const drafts = this.#drainLines(snapshot, active, false);
|
|
169
|
+
if (drafts.length) active.lastFlushAt = now;
|
|
170
|
+
return drafts;
|
|
171
|
+
}
|
|
172
|
+
if (["thinking_start", "thinking_delta", "thinking_end"].includes(update.type) && Number.isInteger(update.contentIndex)) {
|
|
173
|
+
const index = Number(update.contentIndex);
|
|
174
|
+
if (index < 0 || index > 1_000_000_000 || active.emittedEvents >= MAX_MESSAGE_STREAM_EVENTS) { active.truncated = true; return []; }
|
|
175
|
+
const state = update.type === "thinking_start" ? "started" : update.type === "thinking_end" ? "completed" : "streaming";
|
|
176
|
+
if (state === "started" && (active.thinking.has(index) || active.thinkingCompleted.has(index))) return [];
|
|
177
|
+
if (state === "streaming" && (active.thinkingStreaming.has(index) || active.thinkingCompleted.has(index))) return [];
|
|
178
|
+
if (state === "completed" && active.thinkingCompleted.has(index)) return [];
|
|
179
|
+
if (state === "started") active.thinking.add(index); if (state === "streaming") active.thinkingStreaming.add(index);
|
|
180
|
+
if (state === "completed") { active.thinkingCompleted.add(index); active.thinkingStreaming.delete(index); }
|
|
181
|
+
const draft = this.#draft(snapshot, "message.thinking-state", { contentIndex: index, state, redacted: true },
|
|
182
|
+
{ messageRef: active.ref, redacted: true });
|
|
183
|
+
if (draft) active.emittedEvents += 1;
|
|
184
|
+
return draft ? [draft] : [];
|
|
185
|
+
}
|
|
186
|
+
return [];
|
|
187
|
+
}
|
|
188
|
+
messageEnded(event: { message?: unknown }, snapshot: BridgeSnapshot): RuntimeEventDraft[] {
|
|
189
|
+
const message = event.message as any, messageRole = role(message); if (!messageRole) return [];
|
|
190
|
+
const active = this.#activeByRole.get(messageRole); if (!active) return [];
|
|
191
|
+
const drafts = messageRole === "assistant" ? this.#drainLines(snapshot, active, true) : [];
|
|
192
|
+
this.#activeByRole.delete(messageRole); this.#lastMessageRef = active.ref;
|
|
193
|
+
const finalText = messageRole === "tool-result" ? { text: "", redacted: false, truncated: false } : safe(text(message), MAX_STREAM_BUFFER);
|
|
194
|
+
const reason = stopReason(message);
|
|
195
|
+
if (messageRole === "assistant" && (reason === "error" || reason === "aborted")) {
|
|
196
|
+
const error = safe(message?.errorMessage, 500);
|
|
197
|
+
const failed = this.#draft(snapshot, "message.failed", { role: "assistant", reason, errorCode: reason === "error" ? "assistant-message-error" : "assistant-message-aborted",
|
|
198
|
+
message: error.text || null, contentDigest: finalText.text ? digest(finalText.text) : null },
|
|
199
|
+
{ sourceObservedAt: message?.timestamp, messageRef: active.ref, redacted: finalText.redacted || error.redacted, truncated: finalText.truncated || error.truncated });
|
|
200
|
+
if (failed) drafts.push(failed); return drafts;
|
|
201
|
+
}
|
|
202
|
+
const completed = this.#draft(snapshot, "message.completed", { role: messageRole, contentDigest: finalText.text ? digest(finalText.text) : null,
|
|
203
|
+
contentRef: null, textPreview: messageRole === "tool-result" ? null : finalText.text.slice(0, 4_000), textChars: messageRole === "tool-result" ? null : finalText.text.length,
|
|
204
|
+
blockCount: Math.min(10_000, Array.isArray(message?.content) ? message.content.length : finalText.text ? 1 : 0), stopReason: reason, usage: usage(message) },
|
|
205
|
+
{ sourceObservedAt: message?.timestamp, messageRef: active.ref, redacted: finalText.redacted, truncated: finalText.truncated || active.truncated });
|
|
206
|
+
if (completed) drafts.push(completed); return drafts;
|
|
207
|
+
}
|
|
208
|
+
turnEnded(event: { message?: unknown; toolResults?: unknown[] }, snapshot: BridgeSnapshot): RuntimeEventDraft[] {
|
|
209
|
+
const reason = stopReason(event.message), count = Array.isArray(event.toolResults) ? Math.min(10_000, event.toolResults.length) : 0;
|
|
210
|
+
const draft = this.#draft(snapshot, "turn.ended", { phase: "ended", finalMessageRef: this.#lastMessageRef, toolResultCount: count, stopReason: reason });
|
|
211
|
+
return draft ? [draft] : [];
|
|
212
|
+
}
|
|
213
|
+
toolStarted(event: { toolCallId?: unknown; toolName?: unknown }, snapshot: BridgeSnapshot): RuntimeEventDraft[] {
|
|
214
|
+
if (typeof event.toolCallId !== "string" || !event.toolCallId) return [];
|
|
215
|
+
const drafts = this.#activeByRole.get("assistant")
|
|
216
|
+
? this.#drainLines(snapshot, this.#activeByRole.get("assistant") as ActiveMessage, false) : [];
|
|
217
|
+
const name = safeToolName(event.toolName);
|
|
218
|
+
const ref = opaque("tool", [snapshot.identity?.sessionRef, event.toolCallId]), activityRef = opaque("activity", [snapshot.identity?.sessionRef, event.toolCallId]);
|
|
219
|
+
this.#toolRefs.set(event.toolCallId, ref); this.#lastToolProgress.set(event.toolCallId, 0);
|
|
220
|
+
const draft = this.#draft(snapshot, "activity.started", activityPayload("started", activityRef, name), { toolCallId: ref });
|
|
221
|
+
if (draft) drafts.push(draft);
|
|
222
|
+
return drafts;
|
|
223
|
+
}
|
|
224
|
+
toolUpdated(event: { toolCallId?: unknown; toolName?: unknown }, snapshot: BridgeSnapshot): RuntimeEventDraft[] {
|
|
225
|
+
if (typeof event.toolCallId !== "string") return [];
|
|
226
|
+
const now = this.#now().getTime(), last = this.#lastToolProgress.get(event.toolCallId) ?? 0; if (now - last < 250) return [];
|
|
227
|
+
const ref = this.#toolRefs.get(event.toolCallId); if (!ref) return [];
|
|
228
|
+
this.#lastToolProgress.set(event.toolCallId, now);
|
|
229
|
+
const name = safeToolName(event.toolName);
|
|
230
|
+
const activityRef = opaque("activity", [snapshot.identity?.sessionRef, event.toolCallId]);
|
|
231
|
+
const draft = this.#draft(snapshot, "activity.progress", activityPayload("progress", activityRef, name), { toolCallId: ref });
|
|
232
|
+
return draft ? [draft] : [];
|
|
233
|
+
}
|
|
234
|
+
toolEnded(event: { toolCallId?: unknown; toolName?: unknown; isError?: unknown }, snapshot: BridgeSnapshot): RuntimeEventDraft[] {
|
|
235
|
+
if (typeof event.toolCallId !== "string") return [];
|
|
236
|
+
const ref = this.#toolRefs.get(event.toolCallId); if (!ref) return [];
|
|
237
|
+
const name = safeToolName(event.toolName);
|
|
238
|
+
const activityRef = opaque("activity", [snapshot.identity?.sessionRef, event.toolCallId]), state = event.isError === true ? "failed" : "finished";
|
|
239
|
+
this.#toolRefs.delete(event.toolCallId); this.#lastToolProgress.delete(event.toolCallId);
|
|
240
|
+
const draft = this.#draft(snapshot, `activity.${state}`, activityPayload(state, activityRef, name), { toolCallId: ref });
|
|
241
|
+
return draft ? [draft] : [];
|
|
242
|
+
}
|
|
243
|
+
agentSettled(snapshot: BridgeSnapshot, hasPendingMessages: boolean | null): RuntimeEventDraft[] {
|
|
244
|
+
const value = hasPendingMessages === null ? { state: "unknown", value: null, reasonCode: "queue-fact-unavailable" }
|
|
245
|
+
: { state: "known", value: hasPendingMessages, reasonCode: null };
|
|
246
|
+
const draft = this.#draft(snapshot, "agent-operation.settled", { settlement: "completed", lastStopReason: null, hasPendingMessages: value });
|
|
247
|
+
this.reset(); return draft ? [draft] : [];
|
|
248
|
+
}
|
|
249
|
+
}
|