@tpsdev-ai/flair 0.59.0 → 0.63.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -10
- package/SECURITY.md +49 -5
- package/config.yaml +23 -12
- package/dist/bridges/builtins/mem0.js +63 -28
- package/dist/bridges/runtime/execute.js +1 -0
- package/dist/bridges/runtime/import-runner.js +12 -0
- package/dist/bridges/runtime/load-plugin.js +42 -13
- package/dist/bridges/runtime/yaml-loader.js +4 -2
- package/dist/bridges/types.js +1 -0
- package/dist/build-info.json +3 -3
- package/dist/cli.js +1054 -367
- package/dist/commands/agent.js +233 -90
- package/dist/commands/attention.js +4 -3
- package/dist/commands/backup-approval.js +218 -0
- package/dist/commands/backup.js +211 -39
- package/dist/commands/bootstrap.js +3 -1
- package/dist/commands/bridge.js +172 -119
- package/dist/commands/deploy.js +71 -8
- package/dist/commands/doctor.js +711 -146
- package/dist/commands/export.js +57 -23
- package/dist/commands/federation.js +787 -82
- package/dist/commands/grant.js +5 -6
- package/dist/commands/help.js +25 -0
- package/dist/commands/hook.js +155 -2
- package/dist/commands/idp.js +27 -19
- package/dist/commands/import.js +136 -20
- package/dist/commands/init.js +469 -200
- package/dist/commands/integrity.js +387 -0
- package/dist/commands/keys.js +247 -58
- package/dist/commands/mcp.js +108 -52
- package/dist/commands/memory.js +203 -35
- package/dist/commands/migrate-harness-memory.js +3 -2
- package/dist/commands/orgevent.js +51 -47
- package/dist/commands/presence.js +4 -3
- package/dist/commands/principal.js +428 -62
- package/dist/commands/quality.js +13 -1
- package/dist/commands/reembed.js +141 -17
- package/dist/commands/relationship.js +2 -1
- package/dist/commands/rem.js +537 -80
- package/dist/commands/restore.js +413 -65
- package/dist/commands/search.js +6 -4
- package/dist/commands/service.js +235 -40
- package/dist/commands/soul.js +4 -9
- package/dist/commands/status.js +94 -38
- package/dist/commands/test.js +7 -3
- package/dist/commands/upgrade.js +77 -23
- package/dist/commands/workspace.js +13 -11
- package/dist/component-env.js +31 -41
- package/dist/deploy.js +136 -4
- package/dist/doctor-client.js +534 -92
- package/dist/engine-version-contract.js +1 -0
- package/dist/engine-version.js +23 -3
- package/dist/fabric-upgrade.js +12 -2
- package/dist/federation/presence-send.js +139 -0
- package/dist/federation-verify.js +273 -180
- package/dist/hook-install.js +670 -6
- package/dist/install/clients.js +171 -35
- package/dist/keystore.js +72 -0
- package/dist/lib/action-recall-runtime.js +328 -0
- package/dist/lib/agent-home-fields.js +132 -0
- package/dist/lib/agent-home.js +427 -0
- package/dist/lib/agent-id-rule.js +88 -0
- package/dist/lib/agent-roster.js +33 -0
- package/dist/lib/atomic-write.js +1 -1
- package/dist/lib/auth-resolve.js +1069 -60
- package/dist/lib/backup-approval-store.js +612 -0
- package/dist/lib/backup-artifact.js +343 -0
- package/dist/lib/capture-runtime.js +124 -0
- package/dist/lib/config-critical-section.js +212 -25
- package/dist/lib/connect-phase.js +33 -0
- package/dist/lib/credential-status-rule.js +78 -0
- package/dist/lib/daemon-liveness.js +43 -11
- package/dist/lib/doctor-run.js +75 -37
- package/dist/lib/durability-copy.js +10 -0
- package/dist/lib/embedding-space-doctor.js +75 -0
- package/dist/lib/federation-pair-access.js +4 -0
- package/dist/lib/federation-retry-queue.js +283 -0
- package/dist/lib/federation-retry-row.js +101 -0
- package/dist/lib/flair-agent-role.js +4 -0
- package/dist/lib/hub-url.js +12 -0
- package/dist/lib/init-admin-pass.js +88 -12
- package/dist/lib/init-listener-environ.js +1 -2
- package/dist/lib/init-occupied-listener.js +15 -111
- package/dist/lib/init-spawn-attribution.js +73 -0
- package/dist/lib/init-tcp-probe.js +33 -0
- package/dist/lib/instance-identity-row.js +20 -0
- package/dist/lib/instruction-event-contract.js +17 -0
- package/dist/lib/instruction-event-doctor.js +102 -0
- package/dist/lib/launchd-management.js +38 -3
- package/dist/lib/listener-table.js +268 -0
- package/dist/lib/local-delete-instance.js +27 -0
- package/dist/lib/local-instance-pair.js +256 -0
- package/dist/lib/mcp-enable.js +1182 -341
- package/dist/lib/mcp-oauth-env-core.js +133 -0
- package/dist/lib/mcp-oauth-env.js +125 -0
- package/dist/lib/mcp-spec.js +17 -1
- package/dist/lib/memory-attributes.js +4 -0
- package/dist/lib/memory-id-policy.js +46 -0
- package/dist/lib/memory-integrity.js +309 -0
- package/dist/lib/memory-provider-timeout.js +33 -0
- package/dist/lib/memory-purge-response.js +20 -0
- package/dist/lib/mqtt-config.js +132 -0
- package/dist/lib/mqtt-listener-doctor.js +104 -0
- package/dist/lib/open-live-row.js +20 -0
- package/dist/lib/ops-table-count.js +25 -0
- package/dist/lib/ops-url.js +52 -0
- package/dist/lib/owned-pins.js +67 -10
- package/dist/lib/peer-status.js +27 -0
- package/dist/lib/principal-status.js +29 -0
- package/dist/lib/process-start-time.js +76 -12
- package/dist/lib/promotion-content-hash.js +20 -0
- package/dist/lib/proto-safe-record.js +42 -0
- package/dist/lib/record-id-path.js +25 -0
- package/dist/lib/reembed-server-support.js +66 -0
- package/dist/lib/restore-archive.js +760 -0
- package/dist/lib/restore-verify.js +104 -0
- package/dist/lib/scheduler-platform.js +10 -6
- package/dist/lib/secret-keys.js +25 -0
- package/dist/lib/secrets-push.js +50 -22
- package/dist/lib/skill-assignment-preflight.js +159 -0
- package/dist/lib/skill-seed-pending.js +24 -0
- package/dist/lib/skill-seed.js +448 -0
- package/dist/lib/skill-tombstone-doctor.js +133 -0
- package/dist/lib/soul-scope-fields.js +26 -0
- package/dist/lib/stop-start-recovery.js +54 -0
- package/dist/lib/uninstall-purge.js +266 -11
- package/dist/lib/upgrade-prior-liveness.js +2 -1
- package/dist/lib/using-flair-skill.js +87 -0
- package/dist/mcp-client-assertion.js +114 -14
- package/dist/memory-id-checkpoint.js +347 -0
- package/dist/memory-node-compare.js +207 -0
- package/dist/mqtt-off-deploy.js +550 -0
- package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
- package/dist/rem/promote-policy.js +3 -3
- package/dist/rem/restore.js +303 -26
- package/dist/rem/runner.js +317 -96
- package/dist/rem/scheduler.js +21 -4
- package/dist/resources/A2AAdapter.js +131 -178
- package/dist/resources/AdminMemory.js +2 -0
- package/dist/resources/AdminMemoryCandidates.js +116 -0
- package/dist/resources/Agent.js +463 -33
- package/dist/resources/AgentCard.js +4 -0
- package/dist/resources/AgentKeyRegister.js +248 -0
- package/dist/resources/AgentKeyRegistration.js +28 -0
- package/dist/resources/AgentReadPosition.js +7 -0
- package/dist/resources/AgentSeed.js +238 -107
- package/dist/resources/AutoPromoteCandidates.js +413 -78
- package/dist/resources/Credential.js +183 -10
- package/dist/resources/Federation.js +915 -145
- package/dist/resources/FederationRetry.js +140 -0
- package/dist/resources/InstructionVersion.js +220 -0
- package/dist/resources/Integration.js +300 -25
- package/dist/resources/MCPClientMetadata.js +6 -3
- package/dist/resources/Memory.js +3300 -758
- package/dist/resources/MemoryArchive.js +171 -53
- package/dist/resources/MemoryBootstrap.js +122 -61
- package/dist/resources/MemoryCandidate.js +37 -3
- package/dist/resources/MemoryConsolidate.js +2 -2
- package/dist/resources/MemoryDedupStats.js +30 -1
- package/dist/resources/MemoryFeed.js +545 -50
- package/dist/resources/MemoryGrant.js +21 -1
- package/dist/resources/MemoryMaintenance.js +368 -46
- package/dist/resources/MemoryPurge.js +348 -0
- package/dist/resources/MemoryReflect.js +71 -12
- package/dist/resources/MemoryReindex.js +111 -17
- package/dist/resources/Message.js +16 -5
- package/dist/resources/OAuth.js +342 -48
- package/dist/resources/OAuthClient.js +1 -1
- package/dist/resources/OrgEvent.js +405 -19
- package/dist/resources/OrgEventCatchup.js +7 -0
- package/dist/resources/OrgEventMaintenance.js +48 -10
- package/dist/resources/PairingToken.js +1 -1
- package/dist/resources/Presence.js +166 -51
- package/dist/resources/PromoteMemoryCandidate.js +24 -7
- package/dist/resources/RecordUsage.js +2 -4
- package/dist/resources/Relationship.js +23 -0
- package/dist/resources/SemanticSearch.js +63 -32
- package/dist/resources/Soul.js +191 -76
- package/dist/resources/SoulFeed.js +2 -1
- package/dist/resources/TeamDirectory.js +35 -0
- package/dist/resources/WorkspaceLatest.js +4 -0
- package/dist/resources/WorkspaceState.js +21 -1
- package/dist/resources/XAA.js +207 -63
- package/dist/resources/a2a-stream.js +313 -0
- package/dist/resources/a2a-url.js +4 -5
- package/dist/resources/agent-admin.js +10 -1
- package/dist/resources/agent-auth.js +138 -83
- package/dist/resources/agent-read-position-lib.js +4 -1
- package/dist/resources/agent-status-guard.js +9 -7
- package/dist/resources/auth-middleware.js +534 -171
- package/dist/resources/authority-field-guard.js +9 -11
- package/dist/resources/auto-promote-lib.js +8 -5
- package/dist/resources/basic-auth-header.js +21 -0
- package/dist/resources/bm25-index-service.js +4 -5
- package/dist/resources/dedup-cluster.js +6 -1
- package/dist/resources/ed25519-auth.js +1 -1
- package/dist/resources/embedding-space-guard.js +366 -72
- package/dist/resources/embeddings-provider.js +25 -0
- package/dist/resources/engine-version-stamp-boot.js +53 -0
- package/dist/resources/federation-classify.js +161 -0
- package/dist/resources/federation-crypto.js +5 -5
- package/dist/resources/federation-retry-lib.js +60 -0
- package/dist/resources/grant-visibility.js +135 -0
- package/dist/resources/harper-routing.js +83 -0
- package/dist/resources/health.js +163 -22
- package/dist/resources/host-pointer/registry.js +29 -0
- package/dist/resources/host-pointer-adapter.js +1 -0
- package/dist/resources/host-source-citation.js +49 -0
- package/dist/resources/host-source-visibility.js +7 -6
- package/dist/resources/in-process.js +24 -22
- package/dist/resources/instance-create-lock.js +17 -0
- package/dist/resources/instance-identity.js +23 -0
- package/dist/resources/instruction-version-record.js +587 -0
- package/dist/resources/internal-authority.js +13 -0
- package/dist/resources/key-lock.js +3 -3
- package/dist/resources/mcp-handler.js +141 -19
- package/dist/resources/mcp-oauth-env-guard.js +36 -0
- package/dist/resources/mcp-oauth-flag.js +12 -14
- package/dist/resources/mcp-oauth.js +450 -56
- package/dist/resources/mcp-tool-arguments.js +4 -6
- package/dist/resources/mcp-tools.js +187 -40
- package/dist/resources/memory-bootstrap-lib.js +5 -15
- package/dist/resources/memory-declared-attributes.js +4 -1
- package/dist/resources/memory-deletion-history.js +55 -0
- package/dist/resources/memory-durability.js +54 -0
- package/dist/resources/memory-embed-hash.js +144 -0
- package/dist/resources/memory-embedding-value.js +8 -0
- package/dist/resources/memory-host-source.js +32 -7
- package/dist/resources/memory-id-guard.js +75 -0
- package/dist/resources/memory-redaction.js +236 -0
- package/dist/resources/memory-reflect-lib.js +1 -1
- package/dist/resources/memory-supplied-vector.js +72 -0
- package/dist/resources/memory-write-lock.js +489 -0
- package/dist/resources/memory-write-response.js +139 -0
- package/dist/resources/memory-write-transaction.js +243 -0
- package/dist/resources/migration-boot.js +17 -12
- package/dist/resources/migrations/boot-progress.js +25 -0
- package/dist/resources/migrations/data-dir.js +90 -19
- package/dist/resources/migrations/dir-safety.js +61 -3
- package/dist/resources/migrations/embedding-stamp.js +462 -82
- package/dist/resources/migrations/export.js +1 -0
- package/dist/resources/migrations/graph-heal.js +27 -27
- package/dist/resources/migrations/ledger.js +5 -2
- package/dist/resources/migrations/lock.js +870 -77
- package/dist/resources/migrations/progress.js +71 -10
- package/dist/resources/migrations/runner.js +212 -18
- package/dist/resources/migrations/snapshot.js +1 -0
- package/dist/resources/migrations/source-fields.js +5 -5
- package/dist/resources/migrations/state.js +36 -1
- package/dist/resources/migrations/status.js +2 -13
- package/dist/resources/migrations/synthetic-test-migration.js +81 -12
- package/dist/resources/migrations/types.js +26 -1
- package/dist/resources/migrations/visibility-backfill.js +113 -72
- package/dist/resources/oauth-discovery.js +0 -5
- package/dist/resources/object-body-guard.js +40 -0
- package/dist/resources/org-event-created-at.js +133 -0
- package/dist/resources/org-event-reserved.js +92 -0
- package/dist/resources/org-event-write-fault.js +19 -0
- package/dist/resources/originator-instance.js +39 -7
- package/dist/resources/owner-delete-recheck.js +78 -0
- package/dist/resources/owner-field-guard.js +39 -5
- package/dist/resources/owner-scoped-write-policy.js +256 -0
- package/dist/resources/owner-scoped-writes.js +89 -0
- package/dist/resources/path-id-rewrite.js +76 -0
- package/dist/resources/presence-internal.js +5 -5
- package/dist/resources/presence-receipt.js +236 -0
- package/dist/resources/promotion-binding.js +43 -0
- package/dist/resources/promotion-stamp.js +143 -17
- package/dist/resources/protocol-context.js +189 -0
- package/dist/resources/record-owner-guard.js +74 -26
- package/dist/resources/record-type-kit.js +2 -4
- package/dist/resources/record-types.js +1 -1
- package/dist/resources/relay-ops.js +78 -6
- package/dist/resources/replay-store.js +96 -19
- package/dist/resources/request-target.js +163 -0
- package/dist/resources/request-transaction.js +46 -1
- package/dist/resources/search-readiness.js +4 -1
- package/dist/resources/seed-ids.js +9 -0
- package/dist/resources/seed-reservation.js +116 -0
- package/dist/resources/semantic-retrieval-core.js +27 -15
- package/dist/resources/server-row-validation.js +71 -0
- package/dist/resources/skill-manifest.js +24 -14
- package/dist/resources/skill-subject.js +53 -0
- package/dist/resources/skill-version-write.js +789 -0
- package/dist/resources/skill-write-fault.js +20 -0
- package/dist/resources/skill-write-policy.js +68 -0
- package/dist/resources/skill-write.js +67 -7
- package/dist/resources/soul-write-policy.js +26 -7
- package/dist/resources/table-helpers.js +10 -7
- package/dist/resources/table-subscription-policy.js +518 -85
- package/dist/resources/table-subscriptions.js +20 -7
- package/dist/resources/team-directory.js +248 -0
- package/dist/resources/tool-descriptors/index.js +69 -8
- package/dist/resources/txn-pause-point.js +235 -0
- package/dist/resources/usage-recording.js +186 -70
- package/dist/resources/write-back.js +383 -0
- package/dist/resources/write-journal-context.js +5 -0
- package/dist/resources/write-journal.js +289 -0
- package/dist/src/engine-version-contract.js +1 -0
- package/dist/src/keystore.js +72 -0
- package/dist/src/lib/agent-home-fields.js +132 -0
- package/dist/src/lib/agent-id-rule.js +88 -0
- package/dist/src/lib/agent-key-register.js +80 -0
- package/dist/src/lib/atomic-write.js +256 -0
- package/dist/src/lib/credential-status-rule.js +78 -0
- package/dist/src/lib/expired-by-agent.js +37 -0
- package/dist/src/lib/federation-retry-row.js +101 -0
- package/dist/src/lib/flair-agent-role.js +4 -0
- package/dist/src/lib/idp-mapping-rule.js +81 -0
- package/dist/src/lib/instance-identity-row.js +20 -0
- package/dist/src/lib/instruction-event-contract.js +17 -0
- package/dist/src/lib/mcp-oauth-env-core.js +133 -0
- package/dist/src/lib/memory-attributes.js +4 -0
- package/dist/src/lib/memory-id-policy.js +46 -0
- package/dist/src/lib/open-live-row.js +20 -0
- package/dist/src/lib/principal-status.js +29 -0
- package/dist/src/lib/proto-safe-record.js +42 -0
- package/dist/src/lib/reembed-server-support.js +66 -0
- package/dist/src/lib/scheduler-platform.js +10 -6
- package/dist/src/lib/soul-scope-fields.js +26 -0
- package/dist/src/lib/systemd-agent-id.js +38 -0
- package/dist/src/rem/promote-policy.js +3 -3
- package/dist/src/rem/scheduler.js +21 -4
- package/docs/access-control.md +164 -54
- package/docs/api-reference.md +165 -32
- package/docs/auth.md +46 -30
- package/docs/bridges.md +11 -0
- package/docs/claude-code.md +37 -7
- package/docs/deploying-on-fabric.md +178 -0
- package/docs/deployment.md +19 -0
- package/docs/embedding-in-a-harper-app.md +17 -15
- package/docs/entity-vocabulary.md +3 -6
- package/docs/federation.md +61 -3
- package/docs/hosted-on-fabric.md +43 -36
- package/docs/integrations.md +14 -14
- package/docs/mcp-clients.md +12 -7
- package/docs/n8n.md +17 -11
- package/docs/notes/mcp-agent-auth-consumer.md +16 -13
- package/docs/notes/mcp-oauth-model2.md +40 -11
- package/docs/openclaw.md +1 -1
- package/docs/quickstart-fabric.md +4 -4
- package/docs/quickstart.md +12 -4
- package/docs/releasing.md +25 -19
- package/docs/rem.md +32 -3
- package/docs/secrets-and-keys.md +21 -4
- package/docs/standalone-local.md +30 -2
- package/docs/supply-chain-policy.md +34 -16
- package/docs/the-team.md +2 -2
- package/docs/upgrade.md +46 -6
- package/package.json +24 -12
- package/schemas/agent-key-registration.graphql +22 -0
- package/schemas/agent.graphql +6 -3
- package/schemas/federation.graphql +41 -1
- package/schemas/memory.graphql +91 -7
- package/schemas/oauth.graphql +19 -0
- package/schemas/schema.graphql +2 -0
- package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
- package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
- package/dist/resources/soul-adk-guard.js +0 -68
package/dist/resources/XAA.js
CHANGED
|
@@ -5,7 +5,13 @@ import { DEFAULT_HTTP_PORT } from "./a2a-url.js";
|
|
|
5
5
|
import { createHash, randomBytes } from "node:crypto";
|
|
6
6
|
import { createRemoteJWKSet, jwtVerify } from "jose";
|
|
7
7
|
import { stampOriginatorOnCreate } from "./originator-instance.js";
|
|
8
|
-
import {
|
|
8
|
+
import { invalidAgentIdMessage, isValidAgentId } from "../src/lib/agent-id-rule.js";
|
|
9
|
+
import { credentialMapsPrincipal, credentialPrincipalId, isUsableCredential } from "../src/lib/credential-status-rule.js";
|
|
10
|
+
import { withKeyLock } from "./key-lock.js";
|
|
11
|
+
import { withOwnedTransaction } from "./request-transaction.js";
|
|
12
|
+
import { CommittedRowChanged, confirmCommittedRow, sameStoredRow, verifyCommittedFields } from "./write-back.js";
|
|
13
|
+
import { txnPausePoint } from "./txn-pause-point.js";
|
|
14
|
+
import { claimIdJagJti, idJagReplayDeps, ReplayStoreUnavailable, reportReplayStoreGapsAtBoot } from "./replay-store.js";
|
|
9
15
|
/**
|
|
10
16
|
* XAA (Enterprise-Managed Authorization) — ID-JAG validation for Flair.
|
|
11
17
|
*
|
|
@@ -44,6 +50,16 @@ export const ID_JAG_LONGEST_ACCEPTANCE_MS = ID_JAG_MAX_VALIDITY_MS + 2 * CLOCK_S
|
|
|
44
50
|
* (both pinned by test/unit-isolated/xaa-jti-replay.test.ts).
|
|
45
51
|
*/
|
|
46
52
|
export const ID_JAG_REPLAY_RETENTION_S = 90_000;
|
|
53
|
+
// Once per worker thread at boot, with the replay guards' own report: a
|
|
54
|
+
// misconfigured IdJagReplay table is named before the first jwt-bearer grant,
|
|
55
|
+
// not on the first claim.
|
|
56
|
+
export const XAA_JTI_REPLAY_BOOT_STORE = {
|
|
57
|
+
label: "XAA jti",
|
|
58
|
+
deps: idJagReplayDeps,
|
|
59
|
+
minRetentionMs: ID_JAG_LONGEST_ACCEPTANCE_MS,
|
|
60
|
+
retentionBasis: "an assertion can stay acceptable",
|
|
61
|
+
};
|
|
62
|
+
reportReplayStoreGapsAtBoot(XAA_JTI_REPLAY_BOOT_STORE);
|
|
47
63
|
// JWKS remote key set cache per issuer (jose handles caching internally)
|
|
48
64
|
const jwksSetCache = new Map();
|
|
49
65
|
function sha256(input) {
|
|
@@ -126,82 +142,198 @@ export async function validateIdJag(assertion, expectedAudience) {
|
|
|
126
142
|
throw new Error(`domain required but no hd/tid claim present — consumer account rejected`);
|
|
127
143
|
}
|
|
128
144
|
}
|
|
129
|
-
//
|
|
130
|
-
//
|
|
131
|
-
//
|
|
132
|
-
// ID_JAG_REPLAY_RETENTION_S, so the assertion's validity is bounded first.
|
|
145
|
+
// A present jti must be a nonempty string with exp no further ahead than
|
|
146
|
+
// ID_JAG_MAX_VALIDITY_MS plus CLOCK_SKEW_MS. resolveOrCreatePrincipal claims
|
|
147
|
+
// it under the subject lock before provisioning and token issuance.
|
|
133
148
|
if (payload.jti !== undefined) {
|
|
134
149
|
if (typeof payload.jti !== "string" || payload.jti === "")
|
|
135
150
|
throw new Error("jti claim must be a nonempty string");
|
|
136
151
|
if (typeof payload.exp !== "number" || payload.exp * 1000 > Date.now() + ID_JAG_MAX_VALIDITY_MS + CLOCK_SKEW_MS) {
|
|
137
152
|
throw new Error(`an assertion with a jti must carry an exp at most ${ID_JAG_MAX_VALIDITY_MS / 3600_000} hours ahead`);
|
|
138
153
|
}
|
|
139
|
-
const claim = await claimIdJagJti(payload.jti, ID_JAG_LONGEST_ACCEPTANCE_MS);
|
|
140
|
-
if (claim === "replay")
|
|
141
|
-
throw new Error("token replay detected");
|
|
142
|
-
if (claim !== "recorded")
|
|
143
|
-
throw new ReplayStoreUnavailable(`flair.IdJagReplay claim: ${claim}`);
|
|
144
154
|
}
|
|
145
155
|
return { payload: payload, idpConfig };
|
|
146
156
|
}
|
|
147
157
|
/**
|
|
148
158
|
* Resolve or JIT-create a Principal from validated ID-JAG claims.
|
|
159
|
+
*
|
|
160
|
+
* Within one Harper process, the subject's per-key lock serializes the
|
|
161
|
+
* credential lookup and any JIT create. A lock miss refuses the grant (503).
|
|
149
162
|
*/
|
|
150
|
-
async function resolveOrCreatePrincipal(payload, idpConfig) {
|
|
163
|
+
async function resolveOrCreatePrincipal(payload, idpConfig, ctx) {
|
|
164
|
+
const store = databases?.flair?.Credential?.primaryStore;
|
|
165
|
+
const outcome = await withKeyLock(store, [XAA_PRINCIPAL_LOCK_NAMESPACE, idpConfig.id, String(payload.sub)], () => resolveOrCreatePrincipalLocked(payload, idpConfig, ctx), XAA_PRINCIPAL_LOCK_ATTEMPTS, XAA_PRINCIPAL_LOCK_WAIT_MS);
|
|
166
|
+
if (outcome.kind === "done")
|
|
167
|
+
return outcome.value;
|
|
168
|
+
throw new PrincipalProvisionBusy();
|
|
169
|
+
}
|
|
170
|
+
/** The subject's principal-provision lock namespace and wait (resources/key-lock.ts). */
|
|
171
|
+
export const XAA_PRINCIPAL_LOCK_NAMESPACE = "flair-xaa-principal";
|
|
172
|
+
const XAA_PRINCIPAL_LOCK_ATTEMPTS = 200;
|
|
173
|
+
const XAA_PRINCIPAL_LOCK_WAIT_MS = 10;
|
|
174
|
+
/** The named refusal of a grant that lost the principal-provision lock: refused, not retried into a second principal. */
|
|
175
|
+
export class PrincipalProvisionBusy extends Error {
|
|
176
|
+
constructor() {
|
|
177
|
+
super("principal provisioning for this subject is in progress; retry");
|
|
178
|
+
this.name = "PrincipalProvisionBusy";
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* `resolveOrCreatePrincipal`'s check-and-write, run while holding the subject's
|
|
183
|
+
* lock: the credential lookup, and the JIT principal + credential create it
|
|
184
|
+
* falls back to. Never called outside the lock.
|
|
185
|
+
*/
|
|
186
|
+
async function resolveOrCreatePrincipalLocked(payload, idpConfig, ctx) {
|
|
187
|
+
// Claim jti after taking the subject lock, before provisioning and token
|
|
188
|
+
// issuance (flair#2333). A lock miss leaves it unclaimed; a retry can succeed
|
|
189
|
+
// if the assertion remains valid and the later grant steps succeed.
|
|
190
|
+
if (payload.jti !== undefined) {
|
|
191
|
+
const claim = await claimIdJagJti(payload.jti, ID_JAG_LONGEST_ACCEPTANCE_MS);
|
|
192
|
+
if (claim === "replay")
|
|
193
|
+
throw new Error("token replay detected");
|
|
194
|
+
if (claim !== "recorded")
|
|
195
|
+
throw new ReplayStoreUnavailable(`flair.IdJagReplay claim: ${claim}`);
|
|
196
|
+
}
|
|
151
197
|
const idpSubject = payload.sub;
|
|
152
198
|
const email = payload.email ?? payload.preferred_username;
|
|
153
199
|
const displayName = payload.name ?? email ?? idpSubject;
|
|
154
|
-
//
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
200
|
+
// Within one Harper process, the credential lookup and any JIT create run
|
|
201
|
+
// in an owned transaction that commits before the subject lock releases.
|
|
202
|
+
let touchedCredential;
|
|
203
|
+
const principalId = await withOwnedTransaction(ctx, async (owned) => {
|
|
204
|
+
// Look for existing credential with this IdP subject
|
|
205
|
+
for await (const cred of databases.flair.Credential.search({
|
|
206
|
+
conditions: [
|
|
207
|
+
{ attribute: "kind", comparator: "equals", value: "idp" },
|
|
208
|
+
{ attribute: "idpSubject", comparator: "equals", value: idpSubject },
|
|
209
|
+
{ attribute: "idpProvider", comparator: "equals", value: idpConfig.id },
|
|
210
|
+
],
|
|
211
|
+
}, owned)) {
|
|
212
|
+
// A matched credential completes a grant only when its status is
|
|
213
|
+
// "active" AND it names a principal (a non-empty string principalId): the
|
|
214
|
+
// rule the MCP resolver and the principal linker apply
|
|
215
|
+
// (src/lib/credential-status-rule.ts, `credentialMapsPrincipal`).
|
|
216
|
+
// `status` is a nullable String on schemas/agent.graphql whose documented
|
|
217
|
+
// values are "active" and "revoked" (a comment, not an enforced enum); the
|
|
218
|
+
// revoke path writes "revoked". Refuse it by name, naming the stored
|
|
219
|
+
// status, or that the credential names no principal: no credential touch
|
|
220
|
+
// and no OAuth token is written, so its lastUsedAt is left untouched. A
|
|
221
|
+
// present `jti` is claimed — and consumed — before this check, in its own
|
|
222
|
+
// transaction (the claim above, before the owned transaction).
|
|
223
|
+
if (!credentialMapsPrincipal(cred)) {
|
|
224
|
+
const state = isUsableCredential(cred) ? "names no principal" : `has status "${cred.status}"`;
|
|
225
|
+
throw new Error(`IdP credential for this subject ${state}; the jwt-bearer grant is refused`);
|
|
226
|
+
}
|
|
227
|
+
// Test-only: valid names are inert unless fault injection is enabled and
|
|
228
|
+
// armed (resources/txn-pause-point.ts). Holds this touch between the read
|
|
229
|
+
// above and the write below — the interleaving a revoke or delete of this
|
|
230
|
+
// credential would commit in.
|
|
231
|
+
const pause = txnPausePoint("xaa-credential-touch");
|
|
232
|
+
if (pause)
|
|
233
|
+
await pause;
|
|
234
|
+
// Update last used with a fresh lastUsedAt. This handler does not retry
|
|
235
|
+
// the touch: a post-commit mismatch or an unreadable read-back refuses
|
|
236
|
+
// the grant.
|
|
237
|
+
const touchedRow = {
|
|
238
|
+
...cred,
|
|
239
|
+
lastUsedAt: nowISO(),
|
|
240
|
+
};
|
|
241
|
+
await databases.flair.Credential.put(touchedRow, owned);
|
|
242
|
+
// A revoke or a delete committed while this touch was in flight (the
|
|
243
|
+
// read above through the write above) refuses the grant rather than
|
|
244
|
+
// being overwritten by the touch: re-read the COMMITTED row and abort
|
|
245
|
+
// the touch unless it is still this matched, active credential
|
|
246
|
+
// (resources/write-back.ts, confirmCommittedRow — the same confirmation
|
|
247
|
+
// the write-back helper runs once its write is staged). Post-commit
|
|
248
|
+
// verification refuses surviving differences in compared fields or identity.
|
|
249
|
+
try {
|
|
250
|
+
await confirmCommittedRow(databases.flair.Credential, cred.id, (committed) => committed != null && credentialMapsPrincipal(committed) &&
|
|
251
|
+
sameStoredRow(committed, cred) &&
|
|
252
|
+
committed.principalId === cred.principalId &&
|
|
253
|
+
committed.kind === cred.kind &&
|
|
254
|
+
committed.idpSubject === cred.idpSubject &&
|
|
255
|
+
committed.idpProvider === cred.idpProvider);
|
|
256
|
+
}
|
|
257
|
+
catch (err) {
|
|
258
|
+
// Aborting this transaction discards the staged touch. Refuse the grant
|
|
259
|
+
// by name: the credential is gone, revoked, or no longer the one read.
|
|
260
|
+
if (err instanceof CommittedRowChanged) {
|
|
261
|
+
throw new Error("the matched IdP credential changed while the grant was in progress; the jwt-bearer grant is refused");
|
|
262
|
+
}
|
|
263
|
+
throw err;
|
|
264
|
+
}
|
|
265
|
+
// Test-only: inert unless fault injection is enabled and armed. Holds the
|
|
266
|
+
// touch after its final pre-commit confirmation and before its owned
|
|
267
|
+
// transaction commits (flair#2656).
|
|
268
|
+
const commitPause = txnPausePoint("xaa-credential-touch-commit");
|
|
269
|
+
if (commitPause)
|
|
270
|
+
await commitPause;
|
|
271
|
+
// Harper assigns these timestamps; they are not staged application fields.
|
|
272
|
+
const touchedFields = { ...touchedRow };
|
|
273
|
+
delete touchedFields.__createdtime__;
|
|
274
|
+
delete touchedFields.__updatedtime__;
|
|
275
|
+
touchedCredential = { id: String(cred.id), identity: touchedRow, fields: touchedFields };
|
|
276
|
+
return credentialPrincipalId(cred);
|
|
277
|
+
}
|
|
278
|
+
// No existing credential — JIT provision if enabled
|
|
279
|
+
if (!idpConfig.jitProvision) {
|
|
280
|
+
throw new Error(`no principal for IdP subject ${idpSubject} and JIT provisioning is disabled`);
|
|
281
|
+
}
|
|
282
|
+
// Test-only: pause after the lookup finds no credential, before JIT create.
|
|
283
|
+
const pause = txnPausePoint("xaa-principal-provision");
|
|
284
|
+
if (pause)
|
|
285
|
+
await pause;
|
|
286
|
+
const principalId = `usr_${idpSubject.replace(/[^a-zA-Z0-9]/g, "_").slice(0, 20)}_${randomBytes(4).toString("hex")}`;
|
|
287
|
+
// flair#2359 — the shared agent-ID rule. The id above is built to conform,
|
|
288
|
+
// but the rule is enforced on the value that is actually written, so a future
|
|
289
|
+
// change to this construction cannot store an id AgentSeed would refuse.
|
|
290
|
+
if (!isValidAgentId(principalId))
|
|
291
|
+
throw new Error(invalidAgentIdMessage(principalId));
|
|
292
|
+
const now = nowISO();
|
|
293
|
+
// Create principal (via Agent table). flair#1965 r2: a raw Agent create —
|
|
294
|
+
// stamp the local instance id (the Agent resource's post() does not run here).
|
|
295
|
+
const principalRow = {
|
|
296
|
+
id: principalId,
|
|
297
|
+
name: displayName,
|
|
298
|
+
displayName,
|
|
299
|
+
kind: "human",
|
|
300
|
+
type: "human",
|
|
301
|
+
status: "active",
|
|
302
|
+
publicKey: `idp:${idpConfig.id}:${idpSubject}`, // placeholder — humans don't have real Ed25519 keys
|
|
303
|
+
defaultTrustTier: idpConfig.defaultTrustTier ?? "unverified",
|
|
304
|
+
admin: false,
|
|
305
|
+
createdAt: now,
|
|
306
|
+
updatedAt: now,
|
|
307
|
+
};
|
|
308
|
+
await stampOriginatorOnCreate(principalRow);
|
|
309
|
+
await databases.flair.Agent.put(principalRow, owned);
|
|
310
|
+
// Create IdP credential
|
|
163
311
|
await databases.flair.Credential.put({
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
// stamp the local instance id (the Agent resource's post() does not run here).
|
|
177
|
-
const principalRow = {
|
|
178
|
-
id: principalId,
|
|
179
|
-
name: displayName,
|
|
180
|
-
displayName,
|
|
181
|
-
kind: "human",
|
|
182
|
-
type: "human",
|
|
183
|
-
status: "active",
|
|
184
|
-
publicKey: `idp:${idpConfig.id}:${idpSubject}`, // placeholder — humans don't have real Ed25519 keys
|
|
185
|
-
defaultTrustTier: idpConfig.defaultTrustTier ?? "unverified",
|
|
186
|
-
admin: false,
|
|
187
|
-
createdAt: now,
|
|
188
|
-
updatedAt: now,
|
|
189
|
-
};
|
|
190
|
-
await stampOriginatorOnCreate(principalRow);
|
|
191
|
-
await databases.flair.Agent.put(principalRow);
|
|
192
|
-
// Create IdP credential
|
|
193
|
-
await databases.flair.Credential.put({
|
|
194
|
-
id: `cred_idp_${randomBytes(8).toString("hex")}`,
|
|
195
|
-
principalId,
|
|
196
|
-
kind: "idp",
|
|
197
|
-
label: idpConfig.name,
|
|
198
|
-
status: "active",
|
|
199
|
-
idpProvider: idpConfig.id,
|
|
200
|
-
idpSubject,
|
|
201
|
-
idpEmail: email,
|
|
202
|
-
createdAt: now,
|
|
203
|
-
lastUsedAt: now,
|
|
312
|
+
id: `cred_idp_${randomBytes(8).toString("hex")}`,
|
|
313
|
+
principalId,
|
|
314
|
+
kind: "idp",
|
|
315
|
+
label: idpConfig.name,
|
|
316
|
+
status: "active",
|
|
317
|
+
idpProvider: idpConfig.id,
|
|
318
|
+
idpSubject,
|
|
319
|
+
idpEmail: email,
|
|
320
|
+
createdAt: now,
|
|
321
|
+
lastUsedAt: now,
|
|
322
|
+
}, owned);
|
|
323
|
+
return principalId;
|
|
204
324
|
});
|
|
325
|
+
// flair#2656: the commit is not proof the touch landed. Answer the grant only
|
|
326
|
+
// when a fresh committed read shows the staged values on the same row
|
|
327
|
+
// identity; otherwise the grant is refused.
|
|
328
|
+
if (touchedCredential) {
|
|
329
|
+
const verdict = await verifyCommittedFields(databases.flair.Credential, touchedCredential.id, touchedCredential.identity, touchedCredential.fields);
|
|
330
|
+
if (verdict === "unreadable") {
|
|
331
|
+
throw new Error("the matched IdP credential could not be read back after the touch (outcome: unconfirmed); the jwt-bearer grant is refused");
|
|
332
|
+
}
|
|
333
|
+
if (verdict !== "shown") {
|
|
334
|
+
throw new Error("the matched IdP credential's committed state does not show this grant's staged values (outcome: unconfirmed); the jwt-bearer grant is refused");
|
|
335
|
+
}
|
|
336
|
+
}
|
|
205
337
|
return principalId;
|
|
206
338
|
}
|
|
207
339
|
/**
|
|
@@ -221,7 +353,7 @@ export function jwtBearerBaseUrl(env = process.env) {
|
|
|
221
353
|
* Handle the jwt-bearer grant type at the token endpoint.
|
|
222
354
|
* Called from OAuthToken when grant_type is urn:ietf:params:oauth:grant-type:jwt-bearer.
|
|
223
355
|
*/
|
|
224
|
-
export async function handleJwtBearerGrant(data) {
|
|
356
|
+
export async function handleJwtBearerGrant(data, ctx) {
|
|
225
357
|
const assertion = data?.assertion;
|
|
226
358
|
if (!assertion) {
|
|
227
359
|
return new Response(JSON.stringify({
|
|
@@ -233,7 +365,13 @@ export async function handleJwtBearerGrant(data) {
|
|
|
233
365
|
try {
|
|
234
366
|
const { payload, idpConfig } = await validateIdJag(assertion, baseUrl);
|
|
235
367
|
// Resolve or create principal
|
|
236
|
-
const principalId = await resolveOrCreatePrincipal(payload, idpConfig);
|
|
368
|
+
const principalId = await resolveOrCreatePrincipal(payload, idpConfig, ctx);
|
|
369
|
+
// Test-only: pause after the subject lock releases and the owned transaction
|
|
370
|
+
// commits, before this request's transaction commits (flair#2333).
|
|
371
|
+
const released = txnPausePoint("xaa-principal-lock-released");
|
|
372
|
+
if (released)
|
|
373
|
+
await released;
|
|
374
|
+
// Token writes follow the subject lock's release and can fail independently.
|
|
237
375
|
// Determine scopes — intersection of ID-JAG scopes and IdP allowed scopes
|
|
238
376
|
const requestedScopes = (payload.scope ?? "memory:read").split(" ");
|
|
239
377
|
const allowedScopes = idpConfig.allowedScopes?.length
|
|
@@ -290,6 +428,12 @@ export async function handleJwtBearerGrant(data) {
|
|
|
290
428
|
error_description: "replay_store_unavailable",
|
|
291
429
|
}), { status: 503, headers: { "content-type": "application/json" } });
|
|
292
430
|
}
|
|
431
|
+
if (err instanceof PrincipalProvisionBusy) {
|
|
432
|
+
return new Response(JSON.stringify({
|
|
433
|
+
error: "temporarily_unavailable",
|
|
434
|
+
error_description: "principal_provision_in_progress",
|
|
435
|
+
}), { status: 503, headers: { "content-type": "application/json" } });
|
|
436
|
+
}
|
|
293
437
|
return new Response(JSON.stringify({
|
|
294
438
|
error: "invalid_grant",
|
|
295
439
|
error_description: err.message,
|
|
@@ -303,7 +447,7 @@ export async function handleJwtBearerGrant(data) {
|
|
|
303
447
|
export class IdpConfig extends databases.flair.IdpConfig {
|
|
304
448
|
// Admin-only on every path (the "Admin-only" comment was previously unenforced —
|
|
305
449
|
// a pure put() override with no auth check, so the non-rejecting gate let
|
|
306
|
-
// anonymous through to Harper's handler).
|
|
450
|
+
// anonymous through to Harper's handler).
|
|
307
451
|
allowRead() { return allowAdmin(this.getContext?.()); }
|
|
308
452
|
allowCreate() { return allowAdmin(this.getContext?.()); }
|
|
309
453
|
allowUpdate() { return allowAdmin(this.getContext?.()); }
|
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* a2a-stream.ts — the A2A `message/stream` event stream and the JSON-RPC
|
|
3
|
+
* envelope helpers the A2A adapter shares with it.
|
|
4
|
+
*
|
|
5
|
+
* Harper-free on purpose: the stream reads through a `readPage` function the
|
|
6
|
+
* caller supplies, so its lifecycle (opening cursor, polling, cancel, error
|
|
7
|
+
* frames) is pinned by test/unit/a2a-stream.test.ts without a store.
|
|
8
|
+
* resources/A2AAdapter.ts supplies a reader that runs OrgEventCatchup in
|
|
9
|
+
* process with the requesting caller's own context (see callerCatchupReader
|
|
10
|
+
* there); which events a read returns (targeting, expiry) is decided there.
|
|
11
|
+
*
|
|
12
|
+
* Cursor: the stream keeps its own position cursor, passed to each catch-up
|
|
13
|
+
* read as an explicit `after`, so it never moves the durable catch-up watermark
|
|
14
|
+
* and the watermark does not decide what the stream delivers (the catch-up read
|
|
15
|
+
* still looks the watermark up). It starts at streamOpeningPosition(): after
|
|
16
|
+
* every event created in or before the millisecond the stream opened, whatever
|
|
17
|
+
* the event's id. The opening comment and the first read are delayed until the
|
|
18
|
+
* clock has passed that millisecond; when Harper sends the response headers is
|
|
19
|
+
* Harper's, and is not tied to that delay.
|
|
20
|
+
*
|
|
21
|
+
* Wire format (Server-Sent Events):
|
|
22
|
+
* - an opening `: stream open` comment;
|
|
23
|
+
* - `event: org.event`, `data:` a JSON-RPC result `{ type: "event", event }`
|
|
24
|
+
* for each event a read returns, in catch-up position order, until the
|
|
25
|
+
* stream ends;
|
|
26
|
+
* - `event: task.status`, `data:` a JSON-RPC result `{ type: "task", task }`
|
|
27
|
+
* after an `org.event` frame when statusFromOrgEvent() finds a status for
|
|
28
|
+
* the event: from its detail, its `status` or `kind`, or words in its
|
|
29
|
+
* summary (the helper may infer `failed` from `error` in the summary);
|
|
30
|
+
* - `event: error`, `data:` a JSON-RPC error, sent once when a read is
|
|
31
|
+
* refused or fails while the stream is open; the stream then ends. A read
|
|
32
|
+
* that settles after the stream has ended sends nothing.
|
|
33
|
+
*
|
|
34
|
+
* The stream ends when the client disconnects or cancels (the pending poll is
|
|
35
|
+
* cleared and no further read starts), after `maxMs`, at an event whose task
|
|
36
|
+
* id is `taskId` and whose status is terminal (later events in that page are
|
|
37
|
+
* not sent), or after an error frame.
|
|
38
|
+
*/
|
|
39
|
+
import { positionAfterTimestamp } from "./agent-read-position-lib.js";
|
|
40
|
+
export function rpcResult(id, result) {
|
|
41
|
+
return { jsonrpc: "2.0", id: id ?? null, result };
|
|
42
|
+
}
|
|
43
|
+
export function rpcError(id, code, message, data) {
|
|
44
|
+
return {
|
|
45
|
+
jsonrpc: "2.0",
|
|
46
|
+
id: id ?? null,
|
|
47
|
+
error: data === undefined ? { code, message } : { code, message, data },
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
export function orgEventWriteFailure(id, failure) {
|
|
51
|
+
return rpcError(id, -32000, "Server error", {
|
|
52
|
+
error: failure === "validator_missing" ? "org_event_validator_missing" : "org_event_row_invalid",
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
/** Does a Harper-parsed JSON tree hold a BigInt among its enumerable values,
|
|
56
|
+
* at any array or object depth? `JSON.stringify` throws on one, so an intake
|
|
57
|
+
* that must serialize a caller value asks this first and refuses with a
|
|
58
|
+
* caller error. */
|
|
59
|
+
export function containsBigInt(value) {
|
|
60
|
+
const pending = [value];
|
|
61
|
+
const seen = new Set();
|
|
62
|
+
while (pending.length > 0) {
|
|
63
|
+
const current = pending.pop();
|
|
64
|
+
if (typeof current === "bigint")
|
|
65
|
+
return true;
|
|
66
|
+
if (current === null || typeof current !== "object")
|
|
67
|
+
continue;
|
|
68
|
+
if (seen.has(current))
|
|
69
|
+
continue;
|
|
70
|
+
seen.add(current);
|
|
71
|
+
if (Array.isArray(current)) {
|
|
72
|
+
for (const item of current)
|
|
73
|
+
pending.push(item);
|
|
74
|
+
}
|
|
75
|
+
else {
|
|
76
|
+
for (const item of Object.values(current))
|
|
77
|
+
pending.push(item);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
export function cleanText(value) {
|
|
83
|
+
return String(value ?? "").trim();
|
|
84
|
+
}
|
|
85
|
+
function parseJsonSafe(value) {
|
|
86
|
+
if (typeof value !== "string" || !value.trim())
|
|
87
|
+
return null;
|
|
88
|
+
try {
|
|
89
|
+
return JSON.parse(value);
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
function normalizeA2AStatus(statusRaw) {
|
|
96
|
+
const status = cleanText(statusRaw).toLowerCase();
|
|
97
|
+
if (!status)
|
|
98
|
+
return null;
|
|
99
|
+
if (status === "done" || status === "closed" || status === "complete" || status === "completed")
|
|
100
|
+
return "completed";
|
|
101
|
+
if (status === "failed" || status === "error")
|
|
102
|
+
return "failed";
|
|
103
|
+
if (status === "cancelled" || status === "canceled")
|
|
104
|
+
return "canceled";
|
|
105
|
+
if (status === "working" || status === "in_progress" || status === "open" || status === "active" || status === "todo") {
|
|
106
|
+
return "working";
|
|
107
|
+
}
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
function inferStatusFromText(textRaw) {
|
|
111
|
+
const text = cleanText(textRaw).toLowerCase();
|
|
112
|
+
if (!text)
|
|
113
|
+
return null;
|
|
114
|
+
if (text.includes("completed") || text.includes("complete") || text.includes("done"))
|
|
115
|
+
return "completed";
|
|
116
|
+
if (text.includes("failed") || text.includes("error"))
|
|
117
|
+
return "failed";
|
|
118
|
+
if (text.includes("cancelled") || text.includes("canceled"))
|
|
119
|
+
return "canceled";
|
|
120
|
+
if (text.includes("working") || text.includes("started") || text.includes("in progress"))
|
|
121
|
+
return "working";
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
export function taskIdFromEvent(event) {
|
|
125
|
+
const refId = cleanText(event?.refId);
|
|
126
|
+
if (refId.startsWith("bd://")) {
|
|
127
|
+
const taskId = cleanText(refId.slice("bd://".length));
|
|
128
|
+
if (taskId)
|
|
129
|
+
return taskId;
|
|
130
|
+
}
|
|
131
|
+
const detail = parseJsonSafe(event?.detail);
|
|
132
|
+
const fromDetail = cleanText(detail?.taskId ?? detail?.id ?? detail?.task?.id);
|
|
133
|
+
if (fromDetail)
|
|
134
|
+
return fromDetail;
|
|
135
|
+
return null;
|
|
136
|
+
}
|
|
137
|
+
export function statusFromOrgEvent(event) {
|
|
138
|
+
const detail = parseJsonSafe(event?.detail);
|
|
139
|
+
return (normalizeA2AStatus(detail?.status) ??
|
|
140
|
+
normalizeA2AStatus(detail?.task?.status) ??
|
|
141
|
+
normalizeA2AStatus(event?.status) ??
|
|
142
|
+
normalizeA2AStatus(event?.kind) ??
|
|
143
|
+
inferStatusFromText(event?.summary) ??
|
|
144
|
+
null);
|
|
145
|
+
}
|
|
146
|
+
const TERMINAL_STATUSES = new Set(["completed", "failed", "canceled"]);
|
|
147
|
+
/**
|
|
148
|
+
* The stream's opening cursor for a stream opened at `openMs`: the first
|
|
149
|
+
* position of the next millisecond. Every `${createdAt}\t${id}` position whose
|
|
150
|
+
* createdAt is in or before the opening millisecond sorts below it, whatever
|
|
151
|
+
* the id; every position in a later millisecond (with a non-empty id) sorts
|
|
152
|
+
* above it. A cursor of positionAfterTimestamp(<opening millisecond>) would
|
|
153
|
+
* still admit an event created earlier in that same millisecond.
|
|
154
|
+
*/
|
|
155
|
+
export function streamOpeningPosition(openMs) {
|
|
156
|
+
return positionAfterTimestamp(new Date(openMs + 1).toISOString());
|
|
157
|
+
}
|
|
158
|
+
export const A2A_STREAM_POLL_MS = 2000;
|
|
159
|
+
export const A2A_STREAM_MAX_MS = 5 * 60 * 1000;
|
|
160
|
+
function isResponseLike(value) {
|
|
161
|
+
return (value != null &&
|
|
162
|
+
typeof value === "object" &&
|
|
163
|
+
typeof value.status === "number" &&
|
|
164
|
+
typeof value.json === "function");
|
|
165
|
+
}
|
|
166
|
+
async function refusalError(rpcId, response) {
|
|
167
|
+
let detail = null;
|
|
168
|
+
try {
|
|
169
|
+
const body = await response.json();
|
|
170
|
+
detail = body?.error ?? body ?? null;
|
|
171
|
+
}
|
|
172
|
+
catch {
|
|
173
|
+
detail = null;
|
|
174
|
+
}
|
|
175
|
+
if (response.status === 403)
|
|
176
|
+
return rpcError(rpcId, -32001, "Forbidden", { detail });
|
|
177
|
+
if (response.status === 401)
|
|
178
|
+
return rpcError(rpcId, -32001, "Unauthorized", { detail });
|
|
179
|
+
if (response.status === 400)
|
|
180
|
+
return rpcError(rpcId, -32602, "Invalid params", { detail });
|
|
181
|
+
return rpcError(rpcId, -32000, "Server error", { status: response.status, detail });
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* The `message/stream` body. Polls `readPage` from streamOpeningPosition(),
|
|
185
|
+
* draining every page (`hasMore`) on each poll, and schedules the next poll
|
|
186
|
+
* only after the current one finishes, so two reads never overlap.
|
|
187
|
+
*/
|
|
188
|
+
export function orgEventStream(opts) {
|
|
189
|
+
const pollMs = opts.pollMs ?? A2A_STREAM_POLL_MS;
|
|
190
|
+
const maxMs = opts.maxMs ?? A2A_STREAM_MAX_MS;
|
|
191
|
+
const taskId = cleanText(opts.taskId) || null;
|
|
192
|
+
const encoder = new TextEncoder();
|
|
193
|
+
let controller = null;
|
|
194
|
+
let closed = false;
|
|
195
|
+
let pollTimer;
|
|
196
|
+
let maxTimer;
|
|
197
|
+
const now = opts.now ?? Date.now;
|
|
198
|
+
const openMs = now();
|
|
199
|
+
let after = streamOpeningPosition(openMs);
|
|
200
|
+
// Stop scheduling: no poll starts after this. A read already in flight
|
|
201
|
+
// finishes, sees `closed`, and writes nothing.
|
|
202
|
+
const stop = () => {
|
|
203
|
+
closed = true;
|
|
204
|
+
if (pollTimer !== undefined)
|
|
205
|
+
clearTimeout(pollTimer);
|
|
206
|
+
if (maxTimer !== undefined)
|
|
207
|
+
clearTimeout(maxTimer);
|
|
208
|
+
pollTimer = undefined;
|
|
209
|
+
maxTimer = undefined;
|
|
210
|
+
};
|
|
211
|
+
const end = () => {
|
|
212
|
+
if (closed)
|
|
213
|
+
return;
|
|
214
|
+
stop();
|
|
215
|
+
try {
|
|
216
|
+
controller?.close();
|
|
217
|
+
}
|
|
218
|
+
catch { /* already closed or cancelled */ }
|
|
219
|
+
};
|
|
220
|
+
const write = (chunk) => {
|
|
221
|
+
if (closed || !controller)
|
|
222
|
+
return;
|
|
223
|
+
try {
|
|
224
|
+
controller.enqueue(encoder.encode(chunk));
|
|
225
|
+
}
|
|
226
|
+
catch {
|
|
227
|
+
// The consumer is gone; nothing further can be delivered.
|
|
228
|
+
stop();
|
|
229
|
+
}
|
|
230
|
+
};
|
|
231
|
+
const frame = (name, payload) => write(`event: ${name}\ndata: ${JSON.stringify(payload)}\n\n`);
|
|
232
|
+
const fail = (payload) => {
|
|
233
|
+
frame("error", payload);
|
|
234
|
+
end();
|
|
235
|
+
};
|
|
236
|
+
const deliver = (event) => {
|
|
237
|
+
frame("org.event", rpcResult(opts.rpcId, { type: "event", event }));
|
|
238
|
+
const status = statusFromOrgEvent(event);
|
|
239
|
+
if (!status)
|
|
240
|
+
return false;
|
|
241
|
+
const eventTaskId = taskIdFromEvent(event);
|
|
242
|
+
frame("task.status", rpcResult(opts.rpcId, {
|
|
243
|
+
type: "task",
|
|
244
|
+
task: { id: eventTaskId ?? taskId, status },
|
|
245
|
+
}));
|
|
246
|
+
return taskId !== null && eventTaskId === taskId && TERMINAL_STATUSES.has(status);
|
|
247
|
+
};
|
|
248
|
+
const poll = async () => {
|
|
249
|
+
pollTimer = undefined;
|
|
250
|
+
if (closed)
|
|
251
|
+
return;
|
|
252
|
+
try {
|
|
253
|
+
for (;;) {
|
|
254
|
+
const page = await opts.readPage(after);
|
|
255
|
+
if (closed)
|
|
256
|
+
return;
|
|
257
|
+
if (isResponseLike(page)) {
|
|
258
|
+
const error = await refusalError(opts.rpcId, page);
|
|
259
|
+
if (!closed)
|
|
260
|
+
fail(error);
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
if (!page || typeof page !== "object" || !Array.isArray(page.events)) {
|
|
264
|
+
fail(rpcError(opts.rpcId, -32000, "Server error", { detail: "the catch-up read returned no page" }));
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
for (const event of page.events) {
|
|
268
|
+
if (deliver(event)) {
|
|
269
|
+
end();
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
if (closed)
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
if (typeof page.nextAfter === "string" && page.nextAfter)
|
|
276
|
+
after = page.nextAfter;
|
|
277
|
+
if (!page.hasMore || page.events.length === 0)
|
|
278
|
+
break;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
catch (error) {
|
|
282
|
+
if (!closed)
|
|
283
|
+
fail(rpcError(opts.rpcId, -32000, "Server error", { detail: error?.message ?? String(error) }));
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
if (!closed)
|
|
287
|
+
pollTimer = setTimeout(() => { void poll(); }, pollMs);
|
|
288
|
+
};
|
|
289
|
+
return new ReadableStream({
|
|
290
|
+
start(c) {
|
|
291
|
+
controller = c;
|
|
292
|
+
// Hold the opening comment and the first read until the clock has left
|
|
293
|
+
// the opening millisecond (when Harper sends the response headers is
|
|
294
|
+
// not tied to this delay).
|
|
295
|
+
const open = () => {
|
|
296
|
+
pollTimer = undefined;
|
|
297
|
+
if (closed)
|
|
298
|
+
return;
|
|
299
|
+
if (now() <= openMs) {
|
|
300
|
+
pollTimer = setTimeout(open, 1);
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
303
|
+
write(": stream open\n\n");
|
|
304
|
+
maxTimer = setTimeout(end, maxMs);
|
|
305
|
+
pollTimer = setTimeout(() => { void poll(); }, 0);
|
|
306
|
+
};
|
|
307
|
+
open();
|
|
308
|
+
},
|
|
309
|
+
cancel() {
|
|
310
|
+
stop();
|
|
311
|
+
},
|
|
312
|
+
});
|
|
313
|
+
}
|
|
@@ -2,9 +2,8 @@
|
|
|
2
2
|
//
|
|
3
3
|
// A default local Flair install listens on DEFAULT_HTTP_PORT (19926, the
|
|
4
4
|
// CLI's `DEFAULT_PORT` in src/cli.ts), NOT on 9926 (the legacy early-install
|
|
5
|
-
// port). The A2A agent-card `url`
|
|
6
|
-
//
|
|
7
|
-
// hits a dead port.
|
|
5
|
+
// port). The A2A agent-card `url` must reflect the REAL listening port, or a
|
|
6
|
+
// remote A2A peer that follows discovery hits a dead port.
|
|
8
7
|
//
|
|
9
8
|
// Kept free of any harper import so the resolution logic is
|
|
10
9
|
// unit-testable without spinning up Harper (mirrors agentcard-fields.ts —
|
|
@@ -13,8 +12,8 @@
|
|
|
13
12
|
import { harperPortValue } from "../src/lib/harper-port-value.js";
|
|
14
13
|
// The CLI's DEFAULT_HTTP_PORT (src/cli.ts `DEFAULT_PORT`). Keep in sync.
|
|
15
14
|
export const DEFAULT_HTTP_PORT = 19926;
|
|
16
|
-
// Loopback base URL
|
|
17
|
-
//
|
|
15
|
+
// Loopback base URL on the port Flair is ACTUALLY listening on (the agent
|
|
16
|
+
// card's local-only fallback below). Reads the port Harper
|
|
18
17
|
// exposes via HTTP_PORT in the runtime env — never the public/proxy URL.
|
|
19
18
|
// `HTTP_PORT` is parsed through `harperPortValue` so a host-qualified value
|
|
20
19
|
// (`127.0.0.1:19926`, `[::1]:19926`) yields a valid URL rather than a doubled
|