@piagent/platform 1.3.1 → 1.4.1
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 +132 -0
- package/README.md +10 -4
- package/README.vi.md +27 -0
- 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/en/architecture.md +13 -0
- package/docs/herdr-workflow.md +1 -0
- package/docs/languages.json +20 -4
- package/docs/mcp-and-tools.md +125 -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 +37 -0
- package/docs/quality-benchmark.md +1 -0
- package/docs/quickstart-vietnamese.md +3 -2
- package/docs/release-install-policy.md +22 -8
- package/docs/runtime-harness-standard.md +2 -1
- 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 +12 -4
- 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 +71 -0
- package/docs/vercel-docs-site.md +1 -0
- package/docs/vi/architecture.md +13 -0
- package/docs/workflow-recipes.md +1 -0
- package/docs-site/architecture.html +5 -1
- package/docs-site/benchmark.html +5 -1
- package/docs-site/commands.html +5 -1
- package/docs-site/content/en/index.html +49 -0
- package/docs-site/content/en/runtime.html +13 -0
- package/docs-site/content/index.html +49 -0
- package/docs-site/content/runtime.html +28 -0
- package/docs-site/context-engine.html +5 -1
- package/docs-site/en/architecture.html +5 -1
- package/docs-site/en/benchmark.html +5 -1
- package/docs-site/en/commands.html +5 -1
- package/docs-site/en/context-engine.html +5 -1
- package/docs-site/en/index.html +54 -1
- package/docs-site/en/mcp-approval.html +5 -1
- package/docs-site/en/mcp-auth.html +5 -1
- package/docs-site/en/mcp-servers.html +5 -1
- package/docs-site/en/mcp.html +5 -1
- package/docs-site/en/permissions.html +5 -1
- package/docs-site/en/profiles.html +5 -1
- package/docs-site/en/quickstart.html +5 -1
- package/docs-site/en/runtime.html +18 -1
- package/docs-site/en/scope.html +5 -1
- package/docs-site/en/security.html +5 -1
- package/docs-site/en/team.html +5 -1
- package/docs-site/en/whats-new.html +5 -1
- package/docs-site/en/workflows.html +5 -1
- package/docs-site/index.html +54 -1
- package/docs-site/mcp-approval.html +5 -1
- package/docs-site/mcp-auth.html +5 -1
- package/docs-site/mcp-servers.html +5 -1
- package/docs-site/mcp.html +5 -1
- package/docs-site/permissions.html +5 -1
- package/docs-site/profiles.html +5 -1
- package/docs-site/quickstart.html +5 -1
- package/docs-site/runtime.html +33 -1
- package/docs-site/scope.html +5 -1
- package/docs-site/security.html +5 -1
- package/docs-site/team.html +5 -1
- package/docs-site/whats-new.html +5 -1
- package/docs-site/workflows.html +5 -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 +43 -4
- package/packages/piagent-core/README.md +3 -2
- 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/capability-verification-cache.js +17 -7
- package/packages/piagent-core/capabilities/runtime-integrity.js +190 -0
- package/packages/piagent-core/extensions/piagent-guard.ts +80 -272
- package/packages/piagent-core/extensions/redaction-core.d.ts +2 -0
- package/packages/piagent-core/extensions/runtime-evidence.js +12 -1
- package/packages/piagent-core/extensions/shell-reach.ts +250 -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-command-actions.js +1 -1
- package/packages/piagent-core/mcp/mcp-server-catalog.js +139 -9
- 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 +12 -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 +93 -6
- package/packages/piagent-core/runtime/policy/block-remedy.ts +139 -0
- 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 +22 -27
- 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-core/runtime/session/token-economics.js +34 -0
- package/packages/piagent-core/runtime/tools/phase-tool-runtime.ts +2 -1
- package/packages/piagent-core/runtime/workflows/task-intake.ts +5 -0
- package/packages/piagent-core/security/sensitive-data.js +7 -0
- package/packages/piagent-webui/dist/client/assets/index-DwKCWbwd.css +1 -0
- package/packages/piagent-webui/dist/client/assets/index-bu7XpD9Q.js +172 -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 +423 -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/extension-authority.ts +47 -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 +239 -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 +489 -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 +125 -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/build-docs-site.mjs +21 -1
- 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/explain-command.mjs +240 -0
- package/scripts/install-global.sh +105 -4
- package/scripts/mcp-manage.mjs +17 -4
- package/scripts/pi-session-stats.sh +10 -2
- package/scripts/piagent-cli.mjs +30 -3
- package/scripts/piagent-dashboard.mjs +261 -0
- package/scripts/piagent-webui-launcher.mjs +121 -0
- package/scripts/setup.sh +69 -33
- package/scripts/traffic-snapshot.mjs +214 -0
- package/scripts/typescript-loader.mjs +42 -1
- package/scripts/uninstall-global.sh +53 -2
- package/scripts/update-global.mjs +33 -1
- package/scripts/verify-local.sh +257 -0
- package/scripts/verify-release-identity.mjs +4 -1
- package/scripts/verify-translation-pairing.mjs +121 -0
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
import { redactSensitiveText } from "../../piagent-core/security/sensitive-data.js";
|
|
4
|
+
import { GatewayEventStore } from "./gateway-events.ts";
|
|
5
|
+
|
|
6
|
+
const MAX_BUFFER = 65_536;
|
|
7
|
+
const MAX_EVENTS = 128;
|
|
8
|
+
const MAX_DELTA = 16_384;
|
|
9
|
+
const PRIVATE_BEGIN = /-----BEGIN [A-Z ]*PRIVATE KEY-----/;
|
|
10
|
+
const PRIVATE_END = /-----END [A-Z ]*PRIVATE KEY-----/;
|
|
11
|
+
|
|
12
|
+
function clean(value: unknown): string {
|
|
13
|
+
return String(value ?? "").replace(/\u001b(?:[@-_]|\[[0-?]*[ -/]*[@-~])/g, "")
|
|
14
|
+
.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, " ");
|
|
15
|
+
}
|
|
16
|
+
function safeTool(value: unknown): string {
|
|
17
|
+
const safe = redactSensitiveText(clean(value));
|
|
18
|
+
if (safe.redacted) return "redacted-tool";
|
|
19
|
+
return safe.text.replace(/[^A-Za-z0-9._:-]/g, "-").replace(/^[^A-Za-z0-9]+/, "").slice(0, 160) || "tool";
|
|
20
|
+
}
|
|
21
|
+
function ref(prefix: string): string { return `${prefix}_${randomBytes(18).toString("base64url")}`; }
|
|
22
|
+
|
|
23
|
+
export class GatewaySessionStream {
|
|
24
|
+
readonly sessionRef: string;
|
|
25
|
+
readonly operationRef: string;
|
|
26
|
+
readonly #events: GatewayEventStore;
|
|
27
|
+
#messageRef: string | null = null;
|
|
28
|
+
#messageSequence = 0;
|
|
29
|
+
#eventCount = 0;
|
|
30
|
+
#buffer = "";
|
|
31
|
+
#truncated = false;
|
|
32
|
+
#started = false;
|
|
33
|
+
#startListeners: Array<() => void> = [];
|
|
34
|
+
readonly #toolRefs = new Map<string, string>();
|
|
35
|
+
|
|
36
|
+
constructor(options: { sessionRef: string; operationRef: string; events: GatewayEventStore }) {
|
|
37
|
+
this.sessionRef = options.sessionRef; this.operationRef = options.operationRef; this.#events = options.events;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
started(): Promise<void> {
|
|
41
|
+
if (this.#started) return Promise.resolve();
|
|
42
|
+
return new Promise((resolve) => this.#startListeners.push(resolve));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
observe(event: any): void {
|
|
46
|
+
if (event?.type === "agent_start") {
|
|
47
|
+
this.#started = true; for (const resolve of this.#startListeners.splice(0)) resolve(); return;
|
|
48
|
+
}
|
|
49
|
+
if (event?.type === "message_start" && event.message?.role === "assistant") {
|
|
50
|
+
this.#messageRef = ref("message"); this.#buffer = ""; return;
|
|
51
|
+
}
|
|
52
|
+
if (event?.type === "message_update" && event.assistantMessageEvent?.type === "text_delta"
|
|
53
|
+
&& typeof event.assistantMessageEvent.delta === "string") {
|
|
54
|
+
const remaining = MAX_BUFFER - this.#buffer.length;
|
|
55
|
+
if (remaining <= 0) { this.#truncated = true; return; }
|
|
56
|
+
this.#buffer += event.assistantMessageEvent.delta.slice(0, remaining);
|
|
57
|
+
if (event.assistantMessageEvent.delta.length > remaining) this.#truncated = true;
|
|
58
|
+
this.#flush(false); return;
|
|
59
|
+
}
|
|
60
|
+
if (event?.type === "message_end" && event.message?.role === "assistant") { this.#flush(true); return; }
|
|
61
|
+
if (event?.type === "tool_execution_start" && typeof event.toolCallId === "string") {
|
|
62
|
+
const toolCallRef = ref("tool"); this.#toolRefs.set(event.toolCallId, toolCallRef);
|
|
63
|
+
this.#events.publish("tool.started", { sessionRef: this.sessionRef, operationRef: this.operationRef, toolCallRef,
|
|
64
|
+
toolLabel: safeTool(event.toolName), isError: null });
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (event?.type === "tool_execution_end" && typeof event.toolCallId === "string") {
|
|
68
|
+
const toolCallRef = this.#toolRefs.get(event.toolCallId); if (!toolCallRef) return;
|
|
69
|
+
this.#events.publish("tool.completed", { sessionRef: this.sessionRef, operationRef: this.operationRef, toolCallRef,
|
|
70
|
+
toolLabel: safeTool(event.toolName), isError: event.isError === true });
|
|
71
|
+
this.#toolRefs.delete(event.toolCallId);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
#flush(final: boolean): void {
|
|
76
|
+
if (!this.#messageRef || !this.#buffer || this.#eventCount >= MAX_EVENTS) {
|
|
77
|
+
if (this.#eventCount >= MAX_EVENTS) this.#truncated = true;
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
let take = final ? this.#buffer.length : this.#buffer.lastIndexOf("\n") + 1;
|
|
81
|
+
if (take <= 0 && this.#buffer.length >= 1_024) take = this.#buffer.length;
|
|
82
|
+
if (take <= 0) return;
|
|
83
|
+
const candidate = this.#buffer.slice(0, take), privateStart = candidate.search(PRIVATE_BEGIN);
|
|
84
|
+
if (privateStart >= 0 && !PRIVATE_END.test(candidate.slice(privateStart))) {
|
|
85
|
+
if (!final) take = privateStart;
|
|
86
|
+
else {
|
|
87
|
+
const before = redactSensitiveText(clean(candidate.slice(0, privateStart))).text;
|
|
88
|
+
this.#buffer = ""; this.#emit(`${before}[REDACTED_SECRET]`); return;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
if (take <= 0) return;
|
|
92
|
+
const source = this.#buffer.slice(0, take); this.#buffer = this.#buffer.slice(take);
|
|
93
|
+
this.#emit(redactSensitiveText(clean(source)).text);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
#emit(value: string): void {
|
|
97
|
+
for (let offset = 0; offset < value.length; offset += MAX_DELTA) {
|
|
98
|
+
if (this.#eventCount >= MAX_EVENTS) { this.#truncated = true; break; }
|
|
99
|
+
this.#events.publish("message.delta", { sessionRef: this.sessionRef, operationRef: this.operationRef,
|
|
100
|
+
messageRef: this.#messageRef!, messageSequence: this.#messageSequence++, delta: value.slice(offset, offset + MAX_DELTA) });
|
|
101
|
+
this.#eventCount += 1;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
complete(sessionRevision: string): void {
|
|
106
|
+
this.#flush(true);
|
|
107
|
+
if (this.#messageRef) this.#events.publish("message.completed", { sessionRef: this.sessionRef, operationRef: this.operationRef,
|
|
108
|
+
messageRef: this.#messageRef, sessionRevision, truncated: this.#truncated });
|
|
109
|
+
}
|
|
110
|
+
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { pathToFileURL } from "node:url";
|
|
5
|
+
|
|
6
|
+
import { redactSensitiveText } from "../../piagent-core/security/sensitive-data.js";
|
|
7
|
+
|
|
8
|
+
export type McpAdapterModules = {
|
|
9
|
+
loadMcpConfig(overridePath?: string, cwd?: string): any;
|
|
10
|
+
resolveServerUrl(definition: any): string | undefined;
|
|
11
|
+
supportsOAuth(definition: any): boolean;
|
|
12
|
+
createOAuthRuntime(signal?: AbortSignal): any;
|
|
13
|
+
shutdownOAuth(runtime: any): Promise<void>;
|
|
14
|
+
authenticate(name: string, url: string, definition: any, options: any): Promise<string>;
|
|
15
|
+
getAuthStatus(name: string, options: any): Promise<"authenticated" | "expired" | "not_authenticated">;
|
|
16
|
+
getAuthStorageOptions(oauthDir: unknown, cwd?: string): any;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
type Job = {
|
|
20
|
+
jobRef: string;
|
|
21
|
+
sessionRef: string;
|
|
22
|
+
connectionRef: string;
|
|
23
|
+
name: string;
|
|
24
|
+
createdAt: string;
|
|
25
|
+
expiresAt: string;
|
|
26
|
+
state: "running" | "completed" | "failed" | "cancelled";
|
|
27
|
+
authorizationUrl: string | null;
|
|
28
|
+
reasonCode: string | null;
|
|
29
|
+
controller: AbortController;
|
|
30
|
+
runtime: any;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
const MAX_JOBS = 16;
|
|
34
|
+
const JOB_TTL_MS = 10 * 60_000;
|
|
35
|
+
|
|
36
|
+
function safeReason(error: unknown): string {
|
|
37
|
+
if (error instanceof Error && /abort|cancel/i.test(error.message)) return "mcp-oauth-cancelled";
|
|
38
|
+
const detail = error && typeof error === "object" ? error as { name?: unknown; status?: unknown; message?: unknown } : {};
|
|
39
|
+
const registrationRejected = detail.name === "RegistrationRejectedError"
|
|
40
|
+
|| (typeof detail.message === "string" && /Dynamic Client Registration rejected/i.test(detail.message));
|
|
41
|
+
if (registrationRejected && (detail.status === 403
|
|
42
|
+
|| (typeof detail.message === "string" && /HTTP 403/i.test(detail.message)))) return "mcp-oauth-client-not-approved";
|
|
43
|
+
if (registrationRejected) return "mcp-oauth-registration-rejected";
|
|
44
|
+
return "mcp-oauth-failed";
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function safeName(value: string): string {
|
|
48
|
+
return redactSensitiveText(value).text.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim().slice(0, 120) || "MCP";
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function safeAuthorizationUrl(value: string): string {
|
|
52
|
+
const parsed = new URL(value);
|
|
53
|
+
if (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(parsed.hostname))) {
|
|
54
|
+
throw new Error("mcp-oauth-url-invalid");
|
|
55
|
+
}
|
|
56
|
+
if (parsed.username || parsed.password) throw new Error("mcp-oauth-url-invalid");
|
|
57
|
+
return parsed.toString();
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function isLoopbackHttpUrl(value: string | undefined): boolean {
|
|
61
|
+
if (!value) return false;
|
|
62
|
+
try {
|
|
63
|
+
const parsed = new URL(value);
|
|
64
|
+
return parsed.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]", "::1"].includes(parsed.hostname);
|
|
65
|
+
} catch { return false; }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export class McpAuthBroker {
|
|
69
|
+
readonly #adapterRoot: string;
|
|
70
|
+
readonly #moduleLoader: (() => Promise<McpAdapterModules>) | null;
|
|
71
|
+
readonly #jobs = new Map<string, Job>();
|
|
72
|
+
#modules: Promise<McpAdapterModules> | null = null;
|
|
73
|
+
|
|
74
|
+
constructor(agentDir: string, moduleLoader?: () => Promise<McpAdapterModules>) {
|
|
75
|
+
this.#adapterRoot = path.join(agentDir, "npm", "node_modules", "pi-mcp-adapter");
|
|
76
|
+
this.#moduleLoader = moduleLoader ?? null;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async #load(): Promise<McpAdapterModules> {
|
|
80
|
+
if (this.#modules) return await this.#modules;
|
|
81
|
+
if (this.#moduleLoader) {
|
|
82
|
+
this.#modules = this.#moduleLoader();
|
|
83
|
+
return await this.#modules;
|
|
84
|
+
}
|
|
85
|
+
this.#modules = (async () => {
|
|
86
|
+
const files = ["config.ts", "utils.ts", "mcp-auth-flow.ts", "mcp-auth.ts"];
|
|
87
|
+
for (const file of files) {
|
|
88
|
+
const stat = fs.lstatSync(path.join(this.#adapterRoot, file));
|
|
89
|
+
if (!stat.isFile() || stat.isSymbolicLink()) throw new Error("mcp-adapter-auth-unavailable");
|
|
90
|
+
}
|
|
91
|
+
const [config, utils, flow, storage] = await Promise.all(files.map((file) => import(pathToFileURL(path.join(this.#adapterRoot, file)).href)));
|
|
92
|
+
return { loadMcpConfig: config.loadMcpConfig, resolveServerUrl: utils.resolveServerUrl, supportsOAuth: flow.supportsOAuth,
|
|
93
|
+
createOAuthRuntime: flow.createOAuthRuntime, shutdownOAuth: flow.shutdownOAuth, authenticate: flow.authenticate,
|
|
94
|
+
getAuthStatus: flow.getAuthStatus, getAuthStorageOptions: storage.getAuthStorageOptions } as McpAdapterModules;
|
|
95
|
+
})();
|
|
96
|
+
return await this.#modules;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async describe(cwd: string, name: string): Promise<{ oauthSupported: boolean; authState: "connected" | "expired" | "not-connected" | "unavailable" }> {
|
|
100
|
+
try {
|
|
101
|
+
const adapter = await this.#load(), config = adapter.loadMcpConfig(undefined, cwd), definition = config.mcpServers?.[name];
|
|
102
|
+
const url = definition ? adapter.resolveServerUrl(definition) : undefined;
|
|
103
|
+
if (!definition || isLoopbackHttpUrl(url) || !adapter.supportsOAuth(definition)) return { oauthSupported: false, authState: "unavailable" };
|
|
104
|
+
const authStorageOptions = adapter.getAuthStorageOptions(config.settings?.oauthDir, cwd);
|
|
105
|
+
const state = await adapter.getAuthStatus(name, { authStorageOptions });
|
|
106
|
+
return { oauthSupported: true, authState: state === "authenticated" ? "connected" : state === "expired" ? "expired" : "not-connected" };
|
|
107
|
+
} catch { return { oauthSupported: false, authState: "unavailable" }; }
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async start(input: { sessionRef: string; connectionRef: string; cwd: string; name: string }): Promise<ReturnType<McpAuthBroker["read"]>> {
|
|
111
|
+
this.#prune();
|
|
112
|
+
const adapter = await this.#load(), config = adapter.loadMcpConfig(undefined, input.cwd), definition = config.mcpServers?.[input.name];
|
|
113
|
+
const url = definition ? adapter.resolveServerUrl(definition) : undefined;
|
|
114
|
+
if (!definition || isLoopbackHttpUrl(url) || !adapter.supportsOAuth(definition)) throw new Error("mcp-oauth-not-supported");
|
|
115
|
+
if (!url) throw new Error("mcp-oauth-url-unavailable");
|
|
116
|
+
const duplicate = [...this.#jobs.values()].find((job) => job.sessionRef === input.sessionRef && job.connectionRef === input.connectionRef && job.state === "running");
|
|
117
|
+
if (duplicate) return this.read(duplicate.jobRef);
|
|
118
|
+
const controller = new AbortController(), runtime = adapter.createOAuthRuntime(controller.signal), now = new Date();
|
|
119
|
+
const job: Job = { jobRef: `mcp_auth_${randomBytes(24).toString("base64url")}`, sessionRef: input.sessionRef,
|
|
120
|
+
connectionRef: input.connectionRef, name: safeName(input.name), createdAt: now.toISOString(), expiresAt: new Date(now.getTime() + JOB_TTL_MS).toISOString(),
|
|
121
|
+
state: "running", authorizationUrl: null, reasonCode: null, controller, runtime };
|
|
122
|
+
this.#jobs.set(job.jobRef, job);
|
|
123
|
+
const authStorageOptions = adapter.getAuthStorageOptions(config.settings?.oauthDir, input.cwd);
|
|
124
|
+
void adapter.authenticate(input.name, url, definition, { signal: controller.signal, runtime, authStorageOptions,
|
|
125
|
+
onAuthorizationUrl: (authorizationUrl: string) => { if (job.state === "running") job.authorizationUrl = safeAuthorizationUrl(authorizationUrl); }
|
|
126
|
+
}).then(() => { if (job.state === "running") job.state = "completed"; }, (error) => {
|
|
127
|
+
if (job.state !== "running") return; job.state = controller.signal.aborted ? "cancelled" : "failed"; job.reasonCode = safeReason(error);
|
|
128
|
+
}).finally(() => void adapter.shutdownOAuth(runtime).catch(() => undefined));
|
|
129
|
+
return this.read(job.jobRef);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
read(jobRef: string) {
|
|
133
|
+
this.#prune();
|
|
134
|
+
const job = this.#jobs.get(jobRef); if (!job) throw new Error("mcp-oauth-job-not-found");
|
|
135
|
+
return { schemaVersion: 1 as const, version: "piagent-mcp-auth-job-v1" as const, generatedAt: new Date().toISOString(),
|
|
136
|
+
jobRef: job.jobRef, sessionRef: job.sessionRef, connectionRef: job.connectionRef, name: job.name, createdAt: job.createdAt,
|
|
137
|
+
expiresAt: job.expiresAt, state: job.state, authorizationUrl: job.authorizationUrl, reasonCode: job.reasonCode };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async cancel(jobRef: string): Promise<ReturnType<McpAuthBroker["read"]>> {
|
|
141
|
+
const job = this.#jobs.get(jobRef); if (!job) throw new Error("mcp-oauth-job-not-found");
|
|
142
|
+
if (job.state === "running") { job.state = "cancelled"; job.reasonCode = "cancelled-by-user"; job.controller.abort(); }
|
|
143
|
+
return this.read(jobRef);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async close(): Promise<void> {
|
|
147
|
+
for (const job of this.#jobs.values()) if (job.state === "running") { job.state = "cancelled"; job.controller.abort(); }
|
|
148
|
+
this.#jobs.clear();
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
#prune(): void {
|
|
152
|
+
const now = Date.now();
|
|
153
|
+
for (const [jobRef, job] of this.#jobs) if (Date.parse(job.expiresAt) <= now) {
|
|
154
|
+
if (job.state === "running") job.controller.abort(); this.#jobs.delete(jobRef);
|
|
155
|
+
}
|
|
156
|
+
while (this.#jobs.size > MAX_JOBS) this.#jobs.delete(this.#jobs.keys().next().value as string);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
|
|
3
|
+
export function nativeProjectPickerAvailable(): boolean { return process.platform === "darwin"; }
|
|
4
|
+
|
|
5
|
+
export function pickNativeProjectFolders(): Promise<string[]> {
|
|
6
|
+
if (!nativeProjectPickerAvailable()) return Promise.reject(new Error("native-project-picker-unavailable"));
|
|
7
|
+
return new Promise((resolve, reject) => {
|
|
8
|
+
const script = [
|
|
9
|
+
'set chosenFolders to choose folder with prompt "Choose project folders for Piagent" with multiple selections allowed',
|
|
10
|
+
'set output to ""',
|
|
11
|
+
'repeat with chosenFolder in chosenFolders',
|
|
12
|
+
'set output to output & POSIX path of chosenFolder & linefeed',
|
|
13
|
+
'end repeat',
|
|
14
|
+
'return output'
|
|
15
|
+
].join("\n");
|
|
16
|
+
execFile("/usr/bin/osascript", ["-e", script], { timeout: 5 * 60_000, maxBuffer: 64 * 1024 }, (error, stdout) => {
|
|
17
|
+
if (error) { reject(new Error("project-import-cancelled")); return; }
|
|
18
|
+
const selected = [...new Set(stdout.split("\n").map((value) => value.trim()).filter(Boolean))].slice(0, 32);
|
|
19
|
+
if (!selected.length) { reject(new Error("project-import-cancelled")); return; }
|
|
20
|
+
resolve(selected);
|
|
21
|
+
});
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export async function pickNativeProjectFolder(): Promise<string> {
|
|
26
|
+
const [selected] = await pickNativeProjectFolders();
|
|
27
|
+
if (!selected) throw new Error("project-import-cancelled");
|
|
28
|
+
return selected;
|
|
29
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { createRequire } from "node:module";
|
|
5
|
+
import { pathToFileURL } from "node:url";
|
|
6
|
+
|
|
7
|
+
const require = createRequire(import.meta.url);
|
|
8
|
+
|
|
9
|
+
function packageRootFrom(start: string): string | null {
|
|
10
|
+
let current = path.dirname(start);
|
|
11
|
+
while (current !== path.dirname(current)) {
|
|
12
|
+
try {
|
|
13
|
+
const pkg = JSON.parse(fs.readFileSync(path.join(current, "package.json"), "utf8")) as { name?: string };
|
|
14
|
+
if (pkg.name === "@earendil-works/pi-coding-agent") return current;
|
|
15
|
+
} catch {
|
|
16
|
+
// Keep walking toward the package root.
|
|
17
|
+
}
|
|
18
|
+
current = path.dirname(current);
|
|
19
|
+
}
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function installedPiHostRoot(): string {
|
|
24
|
+
try {
|
|
25
|
+
const local = packageRootFrom(require.resolve("@earendil-works/pi-coding-agent"));
|
|
26
|
+
if (local) return local;
|
|
27
|
+
} catch {
|
|
28
|
+
// The operator installation is normally global.
|
|
29
|
+
}
|
|
30
|
+
const executable = execFileSync("which", ["pi"], { encoding: "utf8", timeout: 2_000 }).trim();
|
|
31
|
+
const found = packageRootFrom(fs.realpathSync(executable));
|
|
32
|
+
if (!found) throw new Error("pi-host-unavailable");
|
|
33
|
+
return found;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export async function loadPinnedPiHost(expectedVersion: string): Promise<any> {
|
|
37
|
+
const root = installedPiHostRoot();
|
|
38
|
+
const actual = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8")) as { version?: string };
|
|
39
|
+
if (actual.version !== expectedVersion) throw new Error("pi-host-version-mismatch");
|
|
40
|
+
return await import(pathToFileURL(path.join(root, "dist", "index.js")).href);
|
|
41
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "../ownership/profile-state.ts";
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
5
|
+
import { redactSensitiveText } from "../../piagent-core/security/sensitive-data.js";
|
|
6
|
+
import { projectRefForCwd } from "./session-catalog.ts";
|
|
7
|
+
|
|
8
|
+
const VERSION = "piagent-project-registry-v1";
|
|
9
|
+
const MAX_PROJECTS = 200;
|
|
10
|
+
const MAX_BYTES = 256 * 1024;
|
|
11
|
+
|
|
12
|
+
type ProjectRecord = { projectRef: string; cwd: string; label: string; importedAt: string };
|
|
13
|
+
type RegistryFile = { version: typeof VERSION; projects: ProjectRecord[] };
|
|
14
|
+
export type ProjectProjection = { projectRef: string; placeRef: string; label: string };
|
|
15
|
+
|
|
16
|
+
function cleanLabel(value: string): string {
|
|
17
|
+
return (redactSensitiveText(value).text.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim() || "Project").slice(0, 120);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function validRecord(value: unknown): value is ProjectRecord {
|
|
21
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
22
|
+
const item = value as Partial<ProjectRecord>;
|
|
23
|
+
return Object.keys(item).every((key) => ["projectRef", "cwd", "label", "importedAt"].includes(key))
|
|
24
|
+
&& typeof item.projectRef === "string" && /^project_[A-Za-z0-9_-]{40,80}$/.test(item.projectRef)
|
|
25
|
+
&& typeof item.cwd === "string" && path.isAbsolute(item.cwd) && item.cwd.length <= 4_096
|
|
26
|
+
&& typeof item.label === "string" && item.label.length > 0 && item.label.length <= 120 && !/[\u0000-\u001f\u007f]/.test(item.label)
|
|
27
|
+
&& typeof item.importedAt === "string" && Number.isFinite(Date.parse(item.importedAt));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export class ProjectRegistry {
|
|
31
|
+
readonly file: string;
|
|
32
|
+
readonly #root: string;
|
|
33
|
+
readonly #key: Buffer;
|
|
34
|
+
|
|
35
|
+
constructor(root: string, key: Buffer) {
|
|
36
|
+
this.#root = root;
|
|
37
|
+
this.#key = key;
|
|
38
|
+
this.file = path.join(root, "projects.json");
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
#read(): RegistryFile {
|
|
42
|
+
let stat: fs.Stats;
|
|
43
|
+
try { stat = fs.lstatSync(this.file); }
|
|
44
|
+
catch { return { version: VERSION, projects: [] }; }
|
|
45
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_BYTES) throw new Error("project-registry-file-invalid");
|
|
46
|
+
const descriptor = fs.openSync(this.file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
|
|
47
|
+
try {
|
|
48
|
+
const opened = fs.fstatSync(descriptor);
|
|
49
|
+
if (opened.dev !== stat.dev || opened.ino !== stat.ino || opened.size !== stat.size) throw new Error("project-registry-file-race");
|
|
50
|
+
const value = JSON.parse(fs.readFileSync(descriptor, "utf8")) as Partial<RegistryFile>;
|
|
51
|
+
if (value.version !== VERSION || !Array.isArray(value.projects) || value.projects.length > MAX_PROJECTS
|
|
52
|
+
|| !value.projects.every(validRecord)) throw new Error("project-registry-content-invalid");
|
|
53
|
+
const refs = new Set<string>(), paths = new Set<string>();
|
|
54
|
+
for (const item of value.projects) {
|
|
55
|
+
if (item.projectRef !== projectRefForCwd(this.#key, item.cwd) || refs.has(item.projectRef) || paths.has(item.cwd)) {
|
|
56
|
+
throw new Error("project-registry-content-invalid");
|
|
57
|
+
}
|
|
58
|
+
refs.add(item.projectRef); paths.add(item.cwd);
|
|
59
|
+
}
|
|
60
|
+
return value as RegistryFile;
|
|
61
|
+
} finally { fs.closeSync(descriptor); }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
#write(value: RegistryFile): void {
|
|
65
|
+
const body = Buffer.from(`${JSON.stringify(value)}\n`);
|
|
66
|
+
if (body.length > MAX_BYTES) throw new Error("project-registry-limit");
|
|
67
|
+
const temporary = path.join(this.#root, `.projects-${process.pid}-${randomBytes(8).toString("hex")}.tmp`);
|
|
68
|
+
const descriptor = fs.openSync(temporary, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o600);
|
|
69
|
+
try { fs.writeFileSync(descriptor, body); fs.fsyncSync(descriptor); }
|
|
70
|
+
finally { fs.closeSync(descriptor); }
|
|
71
|
+
fs.renameSync(temporary, this.file); fs.chmodSync(this.file, 0o600);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
register(input: string, now = new Date()): ProjectProjection {
|
|
75
|
+
if (!Number.isFinite(now.getTime())) throw new Error("project-import-time-invalid");
|
|
76
|
+
const cwd = fs.realpathSync(path.resolve(input));
|
|
77
|
+
const stat = fs.lstatSync(cwd);
|
|
78
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || cwd === path.parse(cwd).root) throw new Error("project-import-folder-invalid");
|
|
79
|
+
const current = this.#read(), projectRef = projectRefForCwd(this.#key, cwd);
|
|
80
|
+
const existing = current.projects.find((item) => item.projectRef === projectRef);
|
|
81
|
+
if (!existing) {
|
|
82
|
+
if (current.projects.length >= MAX_PROJECTS) throw new Error("project-registry-limit");
|
|
83
|
+
current.projects.push({ projectRef, cwd, label: cleanLabel(path.basename(cwd)), importedAt: now.toISOString() });
|
|
84
|
+
this.#write(current);
|
|
85
|
+
}
|
|
86
|
+
const item = existing ?? current.projects.at(-1)!;
|
|
87
|
+
return { projectRef: item.projectRef, placeRef: item.projectRef, label: item.label };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
list(): ProjectProjection[] {
|
|
91
|
+
return this.#read().projects.flatMap((item) => {
|
|
92
|
+
try {
|
|
93
|
+
const canonical = fs.realpathSync(item.cwd), stat = fs.lstatSync(canonical);
|
|
94
|
+
return canonical === item.cwd && stat.isDirectory() && !stat.isSymbolicLink()
|
|
95
|
+
? [{ projectRef: item.projectRef, placeRef: item.projectRef, label: item.label }] : [];
|
|
96
|
+
} catch { return []; }
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
resolve(projectRef: string): string | null {
|
|
101
|
+
const item = this.#read().projects.find((candidate) => candidate.projectRef === projectRef);
|
|
102
|
+
if (!item) return null;
|
|
103
|
+
try {
|
|
104
|
+
const canonical = fs.realpathSync(item.cwd), stat = fs.lstatSync(canonical);
|
|
105
|
+
return canonical === item.cwd && stat.isDirectory() && !stat.isSymbolicLink() ? canonical : null;
|
|
106
|
+
} catch { return null; }
|
|
107
|
+
}
|
|
108
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
import { redactSensitiveText } from "../../piagent-core/extensions/redaction-core.js";
|
|
4
|
+
|
|
5
|
+
const JOB_TTL_MS = 10 * 60_000;
|
|
6
|
+
const MAX_EVENTS = 16;
|
|
7
|
+
const REF = /^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/;
|
|
8
|
+
|
|
9
|
+
type AuthPrompt = { signal?: AbortSignal; type: "text" | "secret" | "select" | "manual_code"; message: string; placeholder?: string;
|
|
10
|
+
options?: readonly { id: string; label: string; description?: string }[] };
|
|
11
|
+
type AuthEvent = { type: "info"; message: string; links?: readonly { url: string; label?: string }[] }
|
|
12
|
+
| { type: "auth_url"; url: string; instructions?: string } | { type: "device_code"; userCode: string; verificationUri: string;
|
|
13
|
+
intervalSeconds?: number; expiresInSeconds?: number } | { type: "progress"; message: string };
|
|
14
|
+
type ModelRuntime = { getProviders(): readonly any[]; hasConfiguredAuth(providerId: string): boolean;
|
|
15
|
+
login(providerId: string, type: "oauth", interaction: { signal: AbortSignal; prompt(prompt: AuthPrompt): Promise<string>; notify(event: AuthEvent): void }): Promise<unknown> };
|
|
16
|
+
|
|
17
|
+
type PublicEvent = { sequence: number; type: "info" | "auth-url" | "device-code" | "progress"; message: string | null;
|
|
18
|
+
url: string | null; links: Array<{ url: string; label: string | null }>; userCode: string | null; expiresInSeconds: number | null };
|
|
19
|
+
type PublicPrompt = { promptRef: string; type: AuthPrompt["type"]; message: string; placeholder: string | null;
|
|
20
|
+
options: Array<{ id: string; label: string; description: string | null }> };
|
|
21
|
+
type Job = { jobRef: string; providerRef: string; providerId: string; providerName: string; startedAt: string; expiresAt: string;
|
|
22
|
+
state: "running" | "completed" | "failed" | "cancelled"; events: PublicEvent[]; sequence: number; prompt: PublicPrompt | null;
|
|
23
|
+
promptResolve: ((value: string) => void) | null; promptReject: ((error: Error) => void) | null; controller: AbortController;
|
|
24
|
+
promptOptionValues: Map<string, string> | null; reasonCode: string | null };
|
|
25
|
+
|
|
26
|
+
function safeText(value: unknown, fallback = ""): string {
|
|
27
|
+
const text = redactSensitiveText(typeof value === "string" ? value : fallback).text.replace(/[\u0000-\u001f\u007f]/g, " ").replace(/\s+/g, " ").trim();
|
|
28
|
+
return text.slice(0, 512) || fallback;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function safeHttpsUrl(value: unknown): string | null {
|
|
32
|
+
if (typeof value !== "string" || value.length > 4_096) return null;
|
|
33
|
+
try { const url = new URL(value); return url.protocol === "https:" && !url.username && !url.password ? url.href : null; }
|
|
34
|
+
catch { return null; }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function providerRef(providerId: string): string {
|
|
38
|
+
return `provider.${createHash("sha256").update(providerId).digest("hex")}`;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export class ProviderAuthBroker {
|
|
42
|
+
readonly #runtime: ModelRuntime;
|
|
43
|
+
readonly #jobs = new Map<string, Job>();
|
|
44
|
+
|
|
45
|
+
constructor(runtime: ModelRuntime) { this.#runtime = runtime; }
|
|
46
|
+
|
|
47
|
+
#providers() {
|
|
48
|
+
return this.#runtime.getProviders().filter((provider) => provider?.auth?.oauth).map((provider) => ({
|
|
49
|
+
providerRef: providerRef(String(provider.id)), providerId: String(provider.id), name: safeText(provider.name, String(provider.id)),
|
|
50
|
+
configured: this.#runtime.hasConfiguredAuth(String(provider.id))
|
|
51
|
+
})).sort((a, b) => a.name.localeCompare(b.name));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
catalog() {
|
|
55
|
+
const providers = this.#providers();
|
|
56
|
+
return { schemaVersion: 1, version: "piagent-provider-auth-catalog-v1", generatedAt: new Date().toISOString(),
|
|
57
|
+
state: "ready", providers: providers.map(({ providerRef, name, configured }) => ({ providerRef, name, method: "oauth", state: configured ? "connected" : "not-connected" })),
|
|
58
|
+
reasonCode: providers.length ? null : "no-oauth-provider" };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
#cleanup(): void {
|
|
62
|
+
const now = Date.now();
|
|
63
|
+
for (const [ref, job] of this.#jobs) if (Date.parse(job.expiresAt) <= now) {
|
|
64
|
+
job.controller.abort(); job.promptReject?.(new Error("provider-auth-expired")); this.#jobs.delete(ref);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
#public(job: Job) {
|
|
69
|
+
return { schemaVersion: 1, version: "piagent-provider-auth-job-v1", generatedAt: new Date().toISOString(), jobRef: job.jobRef,
|
|
70
|
+
providerRef: job.providerRef, providerName: job.providerName, startedAt: job.startedAt, expiresAt: job.expiresAt,
|
|
71
|
+
state: job.state, events: job.events, prompt: job.prompt, reasonCode: job.reasonCode };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
read(jobRef: string) {
|
|
75
|
+
this.#cleanup(); if (!REF.test(jobRef)) throw new Error("provider-auth-job-invalid");
|
|
76
|
+
const job = this.#jobs.get(jobRef); if (!job) throw new Error("provider-auth-job-not-found"); return this.#public(job);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
start(command: unknown) {
|
|
80
|
+
this.#cleanup();
|
|
81
|
+
if (!command || typeof command !== "object" || Array.isArray(command)) throw new Error("provider-auth-command-invalid");
|
|
82
|
+
const record = command as Record<string, unknown>;
|
|
83
|
+
if (record.action !== "provider-auth.start" || typeof record.providerRef !== "string" || Object.keys(record).some((key) => !["action", "providerRef"].includes(key))) {
|
|
84
|
+
throw new Error("provider-auth-command-invalid");
|
|
85
|
+
}
|
|
86
|
+
const provider = this.#providers().find((candidate) => candidate.providerRef === record.providerRef);
|
|
87
|
+
if (!provider) throw new Error("provider-auth-provider-not-found");
|
|
88
|
+
const existing = [...this.#jobs.values()].find((job) => job.providerRef === provider.providerRef && job.state === "running");
|
|
89
|
+
if (existing) return this.#public(existing);
|
|
90
|
+
const started = Date.now(), controller = new AbortController();
|
|
91
|
+
const job: Job = { jobRef: `authjob.${randomBytes(24).toString("base64url")}`, providerRef: provider.providerRef,
|
|
92
|
+
providerId: provider.providerId, providerName: provider.name, startedAt: new Date(started).toISOString(),
|
|
93
|
+
expiresAt: new Date(started + JOB_TTL_MS).toISOString(), state: "running", events: [], sequence: 0, prompt: null,
|
|
94
|
+
promptResolve: null, promptReject: null, promptOptionValues: null, controller, reasonCode: null };
|
|
95
|
+
this.#jobs.set(job.jobRef, job);
|
|
96
|
+
void this.#runtime.login(provider.providerId, "oauth", { signal: controller.signal,
|
|
97
|
+
notify: (event) => this.#notify(job, event), prompt: (prompt) => this.#prompt(job, prompt) })
|
|
98
|
+
.then(() => { job.state = "completed"; job.prompt = null; job.promptResolve = null; job.promptReject = null; job.promptOptionValues = null; })
|
|
99
|
+
.catch((error) => { job.state = controller.signal.aborted ? "cancelled" : "failed"; job.prompt = null;
|
|
100
|
+
job.promptResolve = null; job.promptReject = null; job.promptOptionValues = null; job.reasonCode = controller.signal.aborted ? "provider-auth-cancelled"
|
|
101
|
+
: error instanceof Error && error.message.includes("synchron") ? "provider-auth-sync-failed" : "provider-auth-failed"; });
|
|
102
|
+
return this.#public(job);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
#notify(job: Job, event: AuthEvent): void {
|
|
106
|
+
if (job.state !== "running") return;
|
|
107
|
+
let projected: Omit<PublicEvent, "sequence"> | null = null;
|
|
108
|
+
if (event.type === "auth_url") {
|
|
109
|
+
const url = safeHttpsUrl(event.url); if (url) projected = { type: "auth-url", message: safeText(event.instructions) || null,
|
|
110
|
+
url, links: [], userCode: null, expiresInSeconds: null };
|
|
111
|
+
} else if (event.type === "device_code") {
|
|
112
|
+
const url = safeHttpsUrl(event.verificationUri), code = safeText(event.userCode).slice(0, 128);
|
|
113
|
+
if (url && code) projected = { type: "device-code", message: null, url, links: [], userCode: code,
|
|
114
|
+
expiresInSeconds: Number.isFinite(event.expiresInSeconds) ? Math.max(1, Math.min(3600, Number(event.expiresInSeconds))) : null };
|
|
115
|
+
} else if (event.type === "info") projected = { type: "info", message: safeText(event.message) || null, url: null,
|
|
116
|
+
links: (event.links ?? []).slice(0, 6).flatMap((link) => { const url = safeHttpsUrl(link.url); return url ? [{ url, label: safeText(link.label) || null }] : []; }),
|
|
117
|
+
userCode: null, expiresInSeconds: null };
|
|
118
|
+
else projected = { type: "progress", message: safeText(event.message) || null, url: null, links: [], userCode: null, expiresInSeconds: null };
|
|
119
|
+
if (!projected) return;
|
|
120
|
+
job.events.push({ sequence: ++job.sequence, ...projected });
|
|
121
|
+
if (job.events.length > MAX_EVENTS) job.events.splice(0, job.events.length - MAX_EVENTS);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
#prompt(job: Job, prompt: AuthPrompt): Promise<string> {
|
|
125
|
+
if (job.state !== "running" || job.prompt) return Promise.reject(new Error("provider-auth-prompt-conflict"));
|
|
126
|
+
if (prompt.type === "secret") return Promise.reject(new Error("provider-auth-secret-prompt-unsupported"));
|
|
127
|
+
const promptRef = `authprompt.${randomBytes(18).toString("base64url")}`;
|
|
128
|
+
const options = prompt.type === "select" ? (prompt.options ?? []).slice(0, 32).flatMap((option) => {
|
|
129
|
+
if (typeof option.id !== "string" || option.id.length > 1_024) return [];
|
|
130
|
+
const id = `authoption.${randomBytes(18).toString("base64url")}`;
|
|
131
|
+
return [{ id, value: option.id, label: safeText(option.label), description: safeText(option.description) || null }];
|
|
132
|
+
}).filter((option) => option.label) : [];
|
|
133
|
+
job.promptOptionValues = prompt.type === "select" ? new Map(options.map((option) => [option.id, option.value])) : null;
|
|
134
|
+
job.prompt = { promptRef, type: prompt.type, message: safeText(prompt.message, "Authentication"),
|
|
135
|
+
placeholder: safeText(prompt.placeholder) || null,
|
|
136
|
+
options: options.map(({ id, label, description }) => ({ id, label, description })) };
|
|
137
|
+
return new Promise((resolve, reject) => {
|
|
138
|
+
job.promptResolve = resolve; job.promptReject = reject;
|
|
139
|
+
const abort = () => { if (job.prompt?.promptRef === promptRef) { job.prompt = null; job.promptResolve = null; job.promptReject = null;
|
|
140
|
+
job.promptOptionValues = null; reject(new Error("provider-auth-prompt-cancelled")); } };
|
|
141
|
+
if (prompt.signal?.aborted) abort(); else prompt.signal?.addEventListener("abort", abort, { once: true });
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
respond(command: unknown) {
|
|
146
|
+
if (!command || typeof command !== "object" || Array.isArray(command)) throw new Error("provider-auth-response-invalid");
|
|
147
|
+
const record = command as Record<string, unknown>;
|
|
148
|
+
if (record.action !== "provider-auth.respond" || typeof record.jobRef !== "string" || typeof record.promptRef !== "string"
|
|
149
|
+
|| typeof record.value !== "string" || record.value.length > 16_384 || Object.keys(record).some((key) => !["action", "jobRef", "promptRef", "value"].includes(key))) {
|
|
150
|
+
throw new Error("provider-auth-response-invalid");
|
|
151
|
+
}
|
|
152
|
+
const job = this.#jobs.get(record.jobRef); if (!job || job.state !== "running" || job.prompt?.promptRef !== record.promptRef || !job.promptResolve) {
|
|
153
|
+
throw new Error("provider-auth-prompt-stale");
|
|
154
|
+
}
|
|
155
|
+
const answer = job.prompt.type === "select" ? job.promptOptionValues?.get(record.value) : record.value;
|
|
156
|
+
if (answer === undefined) throw new Error("provider-auth-response-invalid");
|
|
157
|
+
const resolve = job.promptResolve; job.prompt = null; job.promptResolve = null; job.promptReject = null; job.promptOptionValues = null; resolve(answer);
|
|
158
|
+
return this.#public(job);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
cancel(command: unknown) {
|
|
162
|
+
if (!command || typeof command !== "object" || Array.isArray(command)) throw new Error("provider-auth-cancel-invalid");
|
|
163
|
+
const record = command as Record<string, unknown>;
|
|
164
|
+
if (record.action !== "provider-auth.cancel" || typeof record.jobRef !== "string" || Object.keys(record).some((key) => !["action", "jobRef"].includes(key))) {
|
|
165
|
+
throw new Error("provider-auth-cancel-invalid");
|
|
166
|
+
}
|
|
167
|
+
const job = this.#jobs.get(record.jobRef); if (!job) throw new Error("provider-auth-job-not-found");
|
|
168
|
+
if (job.state === "running") { job.controller.abort(); job.promptReject?.(new Error("provider-auth-cancelled")); job.prompt = null;
|
|
169
|
+
job.promptResolve = null; job.promptReject = null; job.state = "cancelled"; job.reasonCode = "provider-auth-cancelled"; }
|
|
170
|
+
return this.#public(job);
|
|
171
|
+
}
|
|
172
|
+
}
|