@cursor/july 0.1.39 → 0.1.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +4 -3
- package/dist/bin/agent-serve.js +28 -9
- package/dist/channels/slack/api.d.ts.map +1 -1
- package/dist/channels/slack/api.js +18 -8
- package/dist/channels/slack/attachments.d.ts +82 -0
- package/dist/channels/slack/attachments.d.ts.map +1 -0
- package/dist/channels/slack/attachments.js +520 -0
- package/dist/channels/slack/cursor-account.d.ts +7 -1
- package/dist/channels/slack/cursor-account.d.ts.map +1 -1
- package/dist/channels/slack/cursor-account.js +2 -2
- package/dist/channels/slack/defaults.d.ts.map +1 -1
- package/dist/channels/slack/defaults.js +26 -17
- package/dist/channels/slack/dispatch.d.ts +4 -3
- package/dist/channels/slack/dispatch.d.ts.map +1 -1
- package/dist/channels/slack/dispatch.js +84 -21
- package/dist/channels/slack/inbound.d.ts +6 -0
- package/dist/channels/slack/inbound.d.ts.map +1 -1
- package/dist/channels/slack/inbound.js +48 -2
- package/dist/channels/slack/index.d.ts +1 -0
- package/dist/channels/slack/index.d.ts.map +1 -1
- package/dist/channels/slack/index.js +1 -0
- package/dist/channels/slack/live-delivery.d.ts.map +1 -1
- package/dist/channels/slack/live-delivery.js +16 -4
- package/dist/channels/slack/manifest.d.ts.map +1 -1
- package/dist/channels/slack/manifest.js +1 -0
- package/dist/channels/slack/slack-channel.d.ts.map +1 -1
- package/dist/channels/slack/slack-channel.js +7 -4
- package/dist/channels/slack/types.d.ts +49 -1
- package/dist/channels/slack/types.d.ts.map +1 -1
- package/dist/docs/404.html +2 -2
- package/dist/docs/ab.html +6 -6
- package/dist/docs/assets/{ab.md.6cLOW7--.js → ab.md.hdxsvX5M.js} +2 -2
- package/dist/docs/assets/{app.BQ8Hihdf.js → app.mIw24pb1.js} +1 -1
- package/dist/docs/assets/{building-with-agents.md.txrcGU2B.js → building-with-agents.md.PeZaZA1P.js} +1 -1
- package/dist/docs/assets/chunks/@localSearchIndexroot.BA7V8dEJ.js +1 -0
- package/dist/docs/assets/chunks/{VPLocalSearchBox.BBCr8Yuy.js → VPLocalSearchBox.hOzpPwrG.js} +1 -1
- package/dist/docs/assets/chunks/{theme.CK_NiGC-.js → theme.BtFhUYmh.js} +2 -2
- package/dist/docs/assets/{deployment.md.CuK5SNjN.js → deployment.md.BHVjVqRa.js} +4 -4
- package/dist/docs/assets/{deployment.md.CuK5SNjN.lean.js → deployment.md.BHVjVqRa.lean.js} +1 -1
- package/dist/docs/assets/{evals.md.BQXI3rXy.js → evals.md.qeoGgPw0.js} +3 -3
- package/dist/docs/assets/example-agents_index.md.xmJ87d_3.js +2 -0
- package/dist/docs/assets/{guides_webhooks.md.BERuBSJW.js → guides_webhooks.md.DB-r_er9.js} +47 -4
- package/dist/docs/assets/{guides_webhooks.md.BERuBSJW.lean.js → guides_webhooks.md.DB-r_er9.lean.js} +1 -1
- package/dist/docs/assets/index.md.BKpbkCa6.js +24 -0
- package/dist/docs/assets/{index.md.CmhptOmN.lean.js → index.md.BKpbkCa6.lean.js} +1 -1
- package/dist/docs/assets/{quickstart.md.C_b6ESpD.js → quickstart.md.rIbfahJM.js} +4 -4
- package/dist/docs/assets/{reference_cli.md.Byvrg8eu.js → reference_cli.md.DqEqQpGn.js} +5 -5
- package/dist/docs/assets/{reference_cli.md.Byvrg8eu.lean.js → reference_cli.md.DqEqQpGn.lean.js} +1 -1
- package/dist/docs/assets/{reference_hooks.md.BGDw4VLm.js → reference_hooks.md.BHeG-vjK.js} +2 -2
- package/dist/docs/assets/{reference_hooks.md.BGDw4VLm.lean.js → reference_hooks.md.BHeG-vjK.lean.js} +1 -1
- package/dist/docs/assets/{storage.md.mQDtIULc.js → storage.md.DcGSnIxX.js} +10 -4
- package/dist/docs/assets/{storage.md.mQDtIULc.lean.js → storage.md.DcGSnIxX.lean.js} +1 -1
- package/dist/docs/assets/troubleshooting.md.CkgwmVI0.js +1 -0
- package/dist/docs/assets/{troubleshooting.md.B5RVX_tL.lean.js → troubleshooting.md.CkgwmVI0.lean.js} +1 -1
- package/dist/docs/building-with-agents.html +5 -5
- package/dist/docs/concepts.html +3 -3
- package/dist/docs/deployment.html +6 -6
- package/dist/docs/evals.html +7 -7
- package/dist/docs/example-agents/approval-buddy.html +3 -3
- package/dist/docs/example-agents/benny.html +3 -3
- package/dist/docs/example-agents/bugbot.html +3 -3
- package/dist/docs/example-agents/codebase-wiki.html +3 -3
- package/dist/docs/example-agents/codeowners-review.html +3 -3
- package/dist/docs/example-agents/concierge.html +3 -3
- package/dist/docs/example-agents/fsd.html +3 -3
- package/dist/docs/example-agents/index.html +5 -5
- package/dist/docs/example-agents/knowledge-base.html +3 -3
- package/dist/docs/example-agents/oncall.html +3 -3
- package/dist/docs/example-agents/security-reviewer.html +3 -3
- package/dist/docs/example-agents/slack-agent.html +3 -3
- package/dist/docs/example-agents/weather-agent.html +3 -3
- package/dist/docs/guides/agent-to-agent.html +3 -3
- package/dist/docs/guides/cloud-runtime.html +3 -3
- package/dist/docs/guides/github.html +3 -3
- package/dist/docs/guides/human-in-the-loop.html +3 -3
- package/dist/docs/guides/mcp-oauth.html +3 -3
- package/dist/docs/guides/slack.html +3 -3
- package/dist/docs/guides/webhooks.html +49 -6
- package/dist/docs/hashmap.json +1 -1
- package/dist/docs/hillclimbing.html +3 -3
- package/dist/docs/index.html +7 -7
- package/dist/docs/quickstart.html +8 -8
- package/dist/docs/reference/agent-config.html +3 -3
- package/dist/docs/reference/artifacts.html +3 -3
- package/dist/docs/reference/channels.html +3 -3
- package/dist/docs/reference/cli.html +8 -8
- package/dist/docs/reference/connections.html +3 -3
- package/dist/docs/reference/hooks.html +5 -5
- package/dist/docs/reference/http-api.html +3 -3
- package/dist/docs/reference/instructions.html +3 -3
- package/dist/docs/reference/playground.html +3 -3
- package/dist/docs/reference/project-layout.html +3 -3
- package/dist/docs/reference/prompt.html +3 -3
- package/dist/docs/reference/schedules.html +3 -3
- package/dist/docs/reference/sessions.html +3 -3
- package/dist/docs/reference/skills.html +3 -3
- package/dist/docs/reference/subagents.html +3 -3
- package/dist/docs/reference/tools.html +3 -3
- package/dist/docs/scaffolding-agents.html +3 -3
- package/dist/docs/storage.html +14 -8
- package/dist/docs/troubleshooting.html +5 -5
- package/dist/index.d.ts +4 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/internal/cli-ax.d.ts.map +1 -1
- package/dist/internal/cli-ax.js +22 -2
- package/dist/internal/cli-deploy.d.ts +6 -0
- package/dist/internal/cli-deploy.d.ts.map +1 -1
- package/dist/internal/cli-deploy.js +14 -4
- package/dist/internal/cli-mcp-oauth.d.ts.map +1 -1
- package/dist/internal/cli-mcp-oauth.js +3 -1
- package/dist/internal/cli-mcp.js +4 -4
- package/dist/internal/cursor-event-relay.d.ts +45 -0
- package/dist/internal/cursor-event-relay.d.ts.map +1 -1
- package/dist/internal/cursor-event-relay.js +96 -2
- package/dist/internal/deploy-client.js +1 -1
- package/dist/internal/discovery.d.ts.map +1 -1
- package/dist/internal/discovery.js +35 -7
- package/dist/internal/distribution.d.ts.map +1 -1
- package/dist/internal/distribution.js +3 -1
- package/dist/internal/durable-session-store.d.ts +48 -0
- package/dist/internal/durable-session-store.d.ts.map +1 -0
- package/dist/internal/durable-session-store.js +86 -0
- package/dist/internal/hosting.d.ts +1 -1
- package/dist/internal/hosting.js +2 -2
- package/dist/internal/init-project.d.ts +34 -0
- package/dist/internal/init-project.d.ts.map +1 -1
- package/dist/internal/init-project.js +121 -2
- package/dist/internal/ledger-serving.d.ts +101 -0
- package/dist/internal/ledger-serving.d.ts.map +1 -0
- package/dist/internal/ledger-serving.js +174 -0
- package/dist/internal/listen-port.d.ts +22 -0
- package/dist/internal/listen-port.d.ts.map +1 -0
- package/dist/internal/listen-port.js +77 -0
- package/dist/internal/mcp-oauth.d.ts +12 -1
- package/dist/internal/mcp-oauth.d.ts.map +1 -1
- package/dist/internal/mcp-oauth.js +25 -3
- package/dist/internal/playground/static.d.ts +21 -4
- package/dist/internal/playground/static.d.ts.map +1 -1
- package/dist/internal/playground/static.js +82 -18
- package/dist/internal/sdk-runner.d.ts.map +1 -1
- package/dist/internal/sdk-runner.js +10 -1
- package/dist/internal/server.d.ts.map +1 -1
- package/dist/internal/server.js +67 -49
- package/dist/internal/session-engine.d.ts +57 -1
- package/dist/internal/session-engine.d.ts.map +1 -1
- package/dist/internal/session-engine.js +117 -28
- package/dist/internal/slack-provision-client.js +1 -1
- package/dist/internal/workspace.d.ts +6 -2
- package/dist/internal/workspace.d.ts.map +1 -1
- package/dist/internal/workspace.js +10 -2
- package/dist/kv/memory-kv.d.ts +23 -0
- package/dist/kv/memory-kv.d.ts.map +1 -0
- package/dist/kv/memory-kv.js +103 -0
- package/dist/kv.d.ts +22 -0
- package/dist/kv.d.ts.map +1 -0
- package/dist/kv.js +20 -0
- package/dist/ledger/session-ledger.d.ts +204 -0
- package/dist/ledger/session-ledger.d.ts.map +1 -0
- package/dist/ledger/session-ledger.js +382 -0
- package/dist/ledger.d.ts +11 -0
- package/dist/ledger.d.ts.map +1 -0
- package/dist/ledger.js +9 -0
- package/dist/playground/assets/index-B3HBneZZ.js +85 -0
- package/dist/playground/assets/index-Bqk9nplh.css +1 -0
- package/dist/playground/index.html +2 -2
- package/dist/storage-backends/cursor-hosted.d.ts +25 -3
- package/dist/storage-backends/cursor-hosted.d.ts.map +1 -1
- package/dist/storage-backends/cursor-hosted.js +50 -2
- package/dist/storage-backends/file-kv.d.ts +5 -2
- package/dist/storage-backends/file-kv.d.ts.map +1 -1
- package/dist/storage-backends/file-kv.js +107 -7
- package/dist/storage.d.ts +60 -5
- package/dist/storage.d.ts.map +1 -1
- package/dist/storage.js +28 -4
- package/dist/types.d.ts +123 -3
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +14 -0
- package/docs/README.md +10 -7
- package/docs/ab.md +2 -2
- package/docs/building-with-agents.md +1 -1
- package/docs/deployment.md +34 -11
- package/docs/evals.md +3 -3
- package/docs/example-agents/index.md +1 -1
- package/docs/guides/webhooks.md +87 -0
- package/docs/quickstart.md +7 -8
- package/docs/reference/cli.md +15 -6
- package/docs/reference/hooks.md +8 -2
- package/docs/storage.md +67 -7
- package/docs/troubleshooting.md +10 -2
- package/package.json +20 -7
- package/skills/create-agent/SKILL.md +1 -1
- package/src/bin/agent-serve.ts +27 -11
- package/src/channels/slack/api.ts +19 -14
- package/src/channels/slack/attachments.ts +635 -0
- package/src/channels/slack/cursor-account.ts +8 -0
- package/src/channels/slack/defaults.ts +34 -18
- package/src/channels/slack/dispatch.ts +121 -6
- package/src/channels/slack/inbound.ts +60 -0
- package/src/channels/slack/index.ts +1 -0
- package/src/channels/slack/live-delivery.ts +17 -3
- package/src/channels/slack/manifest.ts +1 -0
- package/src/channels/slack/slack-channel.ts +7 -0
- package/src/channels/slack/types.ts +47 -1
- package/src/index.ts +9 -0
- package/src/internal/cli-ax.ts +25 -1
- package/src/internal/cli-deploy.ts +22 -4
- package/src/internal/cli-mcp-oauth.ts +3 -1
- package/src/internal/cli-mcp.ts +4 -4
- package/src/internal/cursor-event-relay.ts +168 -0
- package/src/internal/deploy-client.ts +1 -1
- package/src/internal/discovery.ts +42 -5
- package/src/internal/distribution.ts +3 -1
- package/src/internal/durable-session-store.ts +95 -0
- package/src/internal/hosting.ts +2 -2
- package/src/internal/init-project.ts +151 -2
- package/src/internal/ledger-serving.ts +240 -0
- package/src/internal/listen-port.ts +85 -0
- package/src/internal/mcp-oauth.ts +29 -4
- package/src/internal/playground/static.ts +111 -20
- package/src/internal/sdk-runner.ts +11 -1
- package/src/internal/server.ts +76 -62
- package/src/internal/session-engine.ts +192 -16
- package/src/internal/slack-provision-client.ts +1 -1
- package/src/internal/workspace.ts +14 -3
- package/src/kv/memory-kv.ts +99 -0
- package/src/kv.ts +27 -0
- package/src/ledger/session-ledger.ts +535 -0
- package/src/ledger.ts +29 -0
- package/src/storage-backends/cursor-hosted.ts +108 -3
- package/src/storage-backends/file-kv.ts +128 -12
- package/src/storage.ts +90 -6
- package/src/types.ts +130 -4
- package/dist/channels/slack/post-update-delivery.d.ts +0 -85
- package/dist/channels/slack/post-update-delivery.d.ts.map +0 -1
- package/dist/docs/assets/chunks/@localSearchIndexroot.B-VTH4As.js +0 -1
- package/dist/docs/assets/example-agents_index.md.DgGBwckv.js +0 -2
- package/dist/docs/assets/index.md.CmhptOmN.js +0 -24
- package/dist/docs/assets/troubleshooting.md.B5RVX_tL.js +0 -1
- package/dist/internal/json-dir-store.d.ts +0 -32
- package/dist/internal/json-dir-store.d.ts.map +0 -1
- package/dist/internal/persistence-coordinator.d.ts +0 -127
- package/dist/internal/persistence-coordinator.d.ts.map +0 -1
- package/dist/multi-tenant.d.ts +0 -80
- package/dist/multi-tenant.d.ts.map +0 -1
- package/dist/multi-tenant.js +0 -69
- package/dist/persistence.d.ts +0 -184
- package/dist/persistence.d.ts.map +0 -1
- package/dist/playground/assets/index-BRhBbnd4.css +0 -1
- package/dist/playground/assets/index-_2WKw9a-.js +0 -85
- package/dist/storage-backends/postgres-kv.d.ts +0 -82
- package/dist/storage-backends/postgres-kv.d.ts.map +0 -1
- package/dist/storage-backends/postgres-kv.js +0 -185
- package/src/storage-backends/postgres-kv.ts +0 -253
- /package/dist/docs/assets/{ab.md.6cLOW7--.lean.js → ab.md.hdxsvX5M.lean.js} +0 -0
- /package/dist/docs/assets/{building-with-agents.md.txrcGU2B.lean.js → building-with-agents.md.PeZaZA1P.lean.js} +0 -0
- /package/dist/docs/assets/{evals.md.BQXI3rXy.lean.js → evals.md.qeoGgPw0.lean.js} +0 -0
- /package/dist/docs/assets/{example-agents_index.md.DgGBwckv.lean.js → example-agents_index.md.xmJ87d_3.lean.js} +0 -0
- /package/dist/docs/assets/{quickstart.md.C_b6ESpD.lean.js → quickstart.md.rIbfahJM.lean.js} +0 -0
|
@@ -0,0 +1,535 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session ledger — coordination only (no inbox).
|
|
3
|
+
*
|
|
4
|
+
* Two key families, driven with CAS over a {@link SessionLedgerKv};
|
|
5
|
+
* agents never touch these keys directly:
|
|
6
|
+
*
|
|
7
|
+
* ```
|
|
8
|
+
* session/<continuationKey> identity, created with put-if-absent
|
|
9
|
+
* ledger/<sessionId> head + lease — every mutation one CAS
|
|
10
|
+
* ```
|
|
11
|
+
*
|
|
12
|
+
* The keys are deliberately bare: namespacing (per agent, per
|
|
13
|
+
* deployment) is not the ledger's concern. The store handle it is given
|
|
14
|
+
* must already be scoped — the engine applies the namespace exactly once
|
|
15
|
+
* where it constructs the handle (see `durable-session-store.ts`), the
|
|
16
|
+
* same boundary where `host.kv` gets its agent scoping.
|
|
17
|
+
*
|
|
18
|
+
* This is a coordination ledger: session identity, one writer per
|
|
19
|
+
* session (leases with generation fencing), and a fenced,
|
|
20
|
+
* ambiguity-safe commit sequence (`head`). It deliberately has **no
|
|
21
|
+
* durable inbox** — no pending list, no payload blobs, no append/drain,
|
|
22
|
+
* no janitor. An event that arrives while the lease is held waits
|
|
23
|
+
* *in-process* on the delivering pod; a crash loses that in-flight
|
|
24
|
+
* event exactly as resident serving does. What ledger mode adds over
|
|
25
|
+
* resident is cross-pod mutual exclusion, zombie fencing, and the
|
|
26
|
+
* committed head sequence. A dead pod needs no janitor: its lease
|
|
27
|
+
* simply expires (~30s) and the next delivery claims at generation+1.
|
|
28
|
+
*
|
|
29
|
+
* The commit is one CAS carrying the read version, the expected `head`,
|
|
30
|
+
* and the holder's `generation` — one committed transition per turn,
|
|
31
|
+
* atomic by construction. Commit always releases the lease: with no
|
|
32
|
+
* pending list there is nothing to keep it for.
|
|
33
|
+
*
|
|
34
|
+
* Clocks: lease expiry compares `expiresAt` against {@link
|
|
35
|
+
* SessionLedgerOptions.clock} (default `Date.now`). Self-hosted N-pod
|
|
36
|
+
* deployments accept NTP-synced pods as a documented requirement; a
|
|
37
|
+
* backend-clock primitive can replace the default without touching the
|
|
38
|
+
* protocol code.
|
|
39
|
+
*/
|
|
40
|
+
|
|
41
|
+
import { newSessionId } from "../internal/ids.js";
|
|
42
|
+
import { keySegment } from "../storage.js";
|
|
43
|
+
import type { HostKvCasApi, JsonObject, JsonValue } from "../types.js";
|
|
44
|
+
|
|
45
|
+
// Lease mechanics: TTL ~30s, heartbeat ~10s, generation increments per
|
|
46
|
+
// acquisition.
|
|
47
|
+
export const LEASE_TTL_MS = 30_000;
|
|
48
|
+
export const HEARTBEAT_INTERVAL_MS = 10_000;
|
|
49
|
+
|
|
50
|
+
const DEFAULT_MAX_CAS_ATTEMPTS = 16;
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Exactly the KV surface the coordination-only ledger uses. `listKeys`
|
|
54
|
+
* is deliberately absent: nothing here scans, so a store must not be
|
|
55
|
+
* rejected for lacking it.
|
|
56
|
+
*/
|
|
57
|
+
export type SessionLedgerKv = Pick<
|
|
58
|
+
HostKvCasApi,
|
|
59
|
+
"getWithVersion" | "putIfAbsent" | "putIfVersion"
|
|
60
|
+
>;
|
|
61
|
+
|
|
62
|
+
/** Runtime probe for {@link SessionLedgerKv} on stores of unknown shape. */
|
|
63
|
+
export function supportsSessionLedgerKv(kv: object): kv is SessionLedgerKv {
|
|
64
|
+
const candidate = kv as Partial<SessionLedgerKv>;
|
|
65
|
+
return (
|
|
66
|
+
typeof candidate.getWithVersion === "function" &&
|
|
67
|
+
typeof candidate.putIfAbsent === "function" &&
|
|
68
|
+
typeof candidate.putIfVersion === "function"
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** `session/<continuationKey>` value. Immutable after creation. */
|
|
73
|
+
export interface SessionIdentity {
|
|
74
|
+
sessionId: string;
|
|
75
|
+
sdkSessionRef: string | null;
|
|
76
|
+
createdAt: number;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export interface LedgerLease {
|
|
80
|
+
holder: string;
|
|
81
|
+
generation: number;
|
|
82
|
+
expiresAt: number;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* `ledger/<sessionId>` value: `{ sessionId, head, lease, generation,
|
|
87
|
+
* lastCommitId }`. `sessionId` lets a future scan address sessions
|
|
88
|
+
* without inverting digested key segments; `generation` is a monotonic
|
|
89
|
+
* acquisition counter that must survive lease release, or a zombie of a
|
|
90
|
+
* cleanly released lease could reuse its generation; `lastCommitId` is
|
|
91
|
+
* the ambiguous-commit recovery token.
|
|
92
|
+
*/
|
|
93
|
+
export interface LedgerSnapshot {
|
|
94
|
+
sessionId: string;
|
|
95
|
+
head: number;
|
|
96
|
+
lease: LedgerLease | null;
|
|
97
|
+
generation: number;
|
|
98
|
+
lastCommitId: string | null;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export type EnsureSessionResult = {
|
|
102
|
+
created: boolean;
|
|
103
|
+
session: SessionIdentity;
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
export type ClaimResult =
|
|
107
|
+
| { claimed: true; lease: LedgerLease; head: number }
|
|
108
|
+
| { claimed: false; reason: "held"; holder: string; expiresAt: number };
|
|
109
|
+
|
|
110
|
+
export type HeartbeatResult =
|
|
111
|
+
| { ok: true; expiresAt: number }
|
|
112
|
+
| { ok: false; reason: "not-found" | "fenced" };
|
|
113
|
+
|
|
114
|
+
export interface CommitArgs {
|
|
115
|
+
/** The holder's lease generation (fences zombies). */
|
|
116
|
+
generation: number;
|
|
117
|
+
/** `head` observed at claim time (fences concurrent turns). */
|
|
118
|
+
expectedHead: number;
|
|
119
|
+
/** Unique per commit attempt; enables ambiguous-outcome recovery. */
|
|
120
|
+
commitId: string;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export interface CommitResult {
|
|
124
|
+
head: number;
|
|
125
|
+
/**
|
|
126
|
+
* Whether this holder's lease is gone — for the caller's purposes, not
|
|
127
|
+
* the record's: `true` also when the re-read of an ambiguous commit
|
|
128
|
+
* finds a *new claimant's* lease, since we no longer hold the session
|
|
129
|
+
* either way and continuing the turn loop would duplicate the new
|
|
130
|
+
* holder's work. On this coordination-only stage every commit
|
|
131
|
+
* releases, so this is always `true`; it exists so callers already
|
|
132
|
+
* branch on it before the inbox makes keep-the-lease outcomes real.
|
|
133
|
+
*/
|
|
134
|
+
leaseReleased: boolean;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* The turn was fenced: a stale generation, a moved head, or a missing
|
|
139
|
+
* ledger. The caller must abort the turn and discard warm state.
|
|
140
|
+
*/
|
|
141
|
+
export class LedgerFencedError extends Error {
|
|
142
|
+
constructor(message: string) {
|
|
143
|
+
super(message);
|
|
144
|
+
this.name = "LedgerFencedError";
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** A CAS retry loop ran out of attempts (sustained contention or outage). */
|
|
149
|
+
export class LedgerCasExhaustedError extends Error {
|
|
150
|
+
constructor(operation: string, attempts: number) {
|
|
151
|
+
super(`${operation}: CAS did not settle after ${attempts} attempts`);
|
|
152
|
+
this.name = "LedgerCasExhaustedError";
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export interface SessionLedgerOptions {
|
|
157
|
+
/** Already-scoped store handle; the ledger writes bare keys into it. */
|
|
158
|
+
kv: SessionLedgerKv;
|
|
159
|
+
/** Stable identity of this pod/process — the lease `holder`. */
|
|
160
|
+
podId: string;
|
|
161
|
+
/** Lease TTL (default {@link LEASE_TTL_MS}). */
|
|
162
|
+
leaseTtlMs?: number;
|
|
163
|
+
/** Time source for lease expiry (default `Date.now`). */
|
|
164
|
+
clock?: () => number;
|
|
165
|
+
/** Max attempts per CAS loop (default 16). */
|
|
166
|
+
maxCasAttempts?: number;
|
|
167
|
+
/**
|
|
168
|
+
* Wait between CAS retries. Default: immediate for the first retries,
|
|
169
|
+
* then a jittered exponential capped at 250ms.
|
|
170
|
+
*/
|
|
171
|
+
backoff?: (attempt: number) => Promise<void>;
|
|
172
|
+
/** Session id mint (default `ses_<24 hex>` like the session engine). */
|
|
173
|
+
newSessionId?: () => string;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
async function defaultBackoff(attempt: number): Promise<void> {
|
|
177
|
+
// The common case is a single conflicting writer (one heartbeat or one
|
|
178
|
+
// claim); retrying immediately wins the next round. Sleep only when
|
|
179
|
+
// contention persists.
|
|
180
|
+
if (attempt < 2) {
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
const cap = Math.min(5 * 2 ** attempt, 250);
|
|
184
|
+
const waitMs = cap / 2 + Math.random() * (cap / 2);
|
|
185
|
+
await new Promise((resolve) => setTimeout(resolve, waitMs));
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Drives the `session/` and `ledger/` key families over a CAS KV. */
|
|
189
|
+
export class SessionLedger {
|
|
190
|
+
private readonly kv: SessionLedgerKv;
|
|
191
|
+
private readonly podId: string;
|
|
192
|
+
private readonly leaseTtlMs: number;
|
|
193
|
+
private readonly clock: () => number;
|
|
194
|
+
private readonly maxCasAttempts: number;
|
|
195
|
+
private readonly backoff: (attempt: number) => Promise<void>;
|
|
196
|
+
private readonly mintSessionId: () => string;
|
|
197
|
+
|
|
198
|
+
constructor(options: SessionLedgerOptions) {
|
|
199
|
+
this.kv = options.kv;
|
|
200
|
+
this.podId = options.podId;
|
|
201
|
+
this.leaseTtlMs = options.leaseTtlMs ?? LEASE_TTL_MS;
|
|
202
|
+
this.clock = options.clock ?? Date.now;
|
|
203
|
+
this.maxCasAttempts = options.maxCasAttempts ?? DEFAULT_MAX_CAS_ATTEMPTS;
|
|
204
|
+
this.backoff = options.backoff ?? defaultBackoff;
|
|
205
|
+
this.mintSessionId = options.newSessionId ?? newSessionId;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
private sessionKey(continuationKey: string): string {
|
|
209
|
+
return `session/${keySegment(continuationKey)}`;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
private ledgerKey(sessionId: string): string {
|
|
213
|
+
return `ledger/${keySegment(sessionId)}`;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Create-or-read the session identity for a continuation key. The create
|
|
218
|
+
* race has one winner (put-if-absent); losers read the winner's identity.
|
|
219
|
+
*/
|
|
220
|
+
async ensureSession(
|
|
221
|
+
continuationKey: string,
|
|
222
|
+
init?: { sdkSessionRef?: string | null }
|
|
223
|
+
): Promise<EnsureSessionResult> {
|
|
224
|
+
const key = this.sessionKey(continuationKey);
|
|
225
|
+
for (let attempt = 0; attempt < this.maxCasAttempts; attempt++) {
|
|
226
|
+
const existing = await this.kv.getWithVersion(key);
|
|
227
|
+
if (existing !== undefined) {
|
|
228
|
+
return {
|
|
229
|
+
created: false,
|
|
230
|
+
session: parseSessionIdentity(existing.value),
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
const session: SessionIdentity = {
|
|
234
|
+
sessionId: this.mintSessionId(),
|
|
235
|
+
sdkSessionRef: init?.sdkSessionRef ?? null,
|
|
236
|
+
createdAt: this.clock(),
|
|
237
|
+
};
|
|
238
|
+
const result = await this.kv.putIfAbsent(key, toJson(session));
|
|
239
|
+
if (result.ok) {
|
|
240
|
+
return { created: true, session };
|
|
241
|
+
}
|
|
242
|
+
if (result.current !== undefined) {
|
|
243
|
+
return {
|
|
244
|
+
created: false,
|
|
245
|
+
session: parseSessionIdentity(result.current.value),
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
// Conflict with no current entry (created then deleted underneath
|
|
249
|
+
// us) — retry from the read.
|
|
250
|
+
await this.backoff(attempt);
|
|
251
|
+
}
|
|
252
|
+
throw new LedgerCasExhaustedError("ensureSession", this.maxCasAttempts);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Try to take the session lease, creating the ledger record on first
|
|
257
|
+
* contact. Succeeds only when the lease is null or expired; the CAS
|
|
258
|
+
* bumps the acquisition generation, fencing every prior holder. A
|
|
259
|
+
* losing caller gets `reason: "held"` and decides whether to wait.
|
|
260
|
+
*/
|
|
261
|
+
async claim(sessionId: string): Promise<ClaimResult> {
|
|
262
|
+
const key = this.ledgerKey(sessionId);
|
|
263
|
+
for (let attempt = 0; attempt < this.maxCasAttempts; attempt++) {
|
|
264
|
+
const entry = await this.kv.getWithVersion(key);
|
|
265
|
+
if (entry === undefined) {
|
|
266
|
+
const initial: LedgerSnapshot = {
|
|
267
|
+
sessionId,
|
|
268
|
+
head: 0,
|
|
269
|
+
lease: null,
|
|
270
|
+
generation: 0,
|
|
271
|
+
lastCommitId: null,
|
|
272
|
+
};
|
|
273
|
+
const result = await this.kv.putIfAbsent(key, toJson(initial));
|
|
274
|
+
// Won or lost, the record now exists — loop back and claim it.
|
|
275
|
+
if (!result.ok) {
|
|
276
|
+
await this.backoff(attempt);
|
|
277
|
+
}
|
|
278
|
+
continue;
|
|
279
|
+
}
|
|
280
|
+
const ledger = parseLedgerSnapshot(entry.value);
|
|
281
|
+
const now = this.clock();
|
|
282
|
+
if (ledger.lease !== null && ledger.lease.expiresAt > now) {
|
|
283
|
+
return {
|
|
284
|
+
claimed: false,
|
|
285
|
+
reason: "held",
|
|
286
|
+
holder: ledger.lease.holder,
|
|
287
|
+
expiresAt: ledger.lease.expiresAt,
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
const lease: LedgerLease = {
|
|
291
|
+
holder: this.podId,
|
|
292
|
+
generation: ledger.generation + 1,
|
|
293
|
+
expiresAt: now + this.leaseTtlMs,
|
|
294
|
+
};
|
|
295
|
+
const next: LedgerSnapshot = {
|
|
296
|
+
...ledger,
|
|
297
|
+
generation: lease.generation,
|
|
298
|
+
lease,
|
|
299
|
+
};
|
|
300
|
+
const result = await this.kv.putIfVersion(
|
|
301
|
+
key,
|
|
302
|
+
toJson(next),
|
|
303
|
+
entry.version
|
|
304
|
+
);
|
|
305
|
+
if (result.ok) {
|
|
306
|
+
return { claimed: true, lease, head: next.head };
|
|
307
|
+
}
|
|
308
|
+
await this.backoff(attempt);
|
|
309
|
+
}
|
|
310
|
+
throw new LedgerCasExhaustedError("claim", this.maxCasAttempts);
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* Extend the lease. Fails when the generation is no longer ours — the
|
|
315
|
+
* caller must abort the turn and discard warm state; the session has a
|
|
316
|
+
* new legitimate holder.
|
|
317
|
+
*/
|
|
318
|
+
async heartbeat(
|
|
319
|
+
sessionId: string,
|
|
320
|
+
generation: number
|
|
321
|
+
): Promise<HeartbeatResult> {
|
|
322
|
+
const key = this.ledgerKey(sessionId);
|
|
323
|
+
for (let attempt = 0; attempt < this.maxCasAttempts; attempt++) {
|
|
324
|
+
const entry = await this.kv.getWithVersion(key);
|
|
325
|
+
if (entry === undefined) {
|
|
326
|
+
return { ok: false, reason: "not-found" };
|
|
327
|
+
}
|
|
328
|
+
const ledger = parseLedgerSnapshot(entry.value);
|
|
329
|
+
if (
|
|
330
|
+
ledger.lease === null ||
|
|
331
|
+
ledger.lease.holder !== this.podId ||
|
|
332
|
+
ledger.lease.generation !== generation
|
|
333
|
+
) {
|
|
334
|
+
return { ok: false, reason: "fenced" };
|
|
335
|
+
}
|
|
336
|
+
const expiresAt = this.clock() + this.leaseTtlMs;
|
|
337
|
+
const next: LedgerSnapshot = {
|
|
338
|
+
...ledger,
|
|
339
|
+
lease: { ...ledger.lease, expiresAt },
|
|
340
|
+
};
|
|
341
|
+
const result = await this.kv.putIfVersion(
|
|
342
|
+
key,
|
|
343
|
+
toJson(next),
|
|
344
|
+
entry.version
|
|
345
|
+
);
|
|
346
|
+
if (result.ok) {
|
|
347
|
+
return { ok: true, expiresAt };
|
|
348
|
+
}
|
|
349
|
+
// Version conflict here is a concurrent writer, not a lost lease —
|
|
350
|
+
// the re-read revalidates the generation before trying again.
|
|
351
|
+
await this.backoff(attempt);
|
|
352
|
+
}
|
|
353
|
+
throw new LedgerCasExhaustedError("heartbeat", this.maxCasAttempts);
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* Commit one turn. The single CAS is the commit point: it bumps `head`,
|
|
358
|
+
* releases the lease, and records `commitId` — atomically.
|
|
359
|
+
*
|
|
360
|
+
* Ambiguous outcomes (the KV threw and we never saw the CAS result) are
|
|
361
|
+
* resolved by re-reading, never by blind-retrying: `head` advanced to
|
|
362
|
+
* `expectedHead + 1` with our `commitId` ⇒ our write landed, report
|
|
363
|
+
* success; `head` still at `expectedHead` with our lease ⇒ it did not,
|
|
364
|
+
* retry against the fresh version; anything else ⇒ fenced.
|
|
365
|
+
*/
|
|
366
|
+
async commit(sessionId: string, args: CommitArgs): Promise<CommitResult> {
|
|
367
|
+
const key = this.ledgerKey(sessionId);
|
|
368
|
+
for (let attempt = 0; attempt < this.maxCasAttempts; attempt++) {
|
|
369
|
+
const entry = await this.kv.getWithVersion(key);
|
|
370
|
+
if (entry === undefined) {
|
|
371
|
+
throw new LedgerFencedError(
|
|
372
|
+
`commit(${sessionId}): ledger key is missing`
|
|
373
|
+
);
|
|
374
|
+
}
|
|
375
|
+
const ledger = parseLedgerSnapshot(entry.value);
|
|
376
|
+
if (
|
|
377
|
+
ledger.head === args.expectedHead + 1 &&
|
|
378
|
+
ledger.lastCommitId === args.commitId
|
|
379
|
+
) {
|
|
380
|
+
// A previous attempt landed even though its result was lost. The
|
|
381
|
+
// lease is released *for us* unless the observed lease is exactly
|
|
382
|
+
// ours: a non-null lease here belongs to a claimant who took the
|
|
383
|
+
// session after our releasing write, and reporting it as "still
|
|
384
|
+
// held" would keep the caller's turn loop alive alongside the new
|
|
385
|
+
// holder's.
|
|
386
|
+
const stillOurs =
|
|
387
|
+
ledger.lease !== null &&
|
|
388
|
+
ledger.lease.holder === this.podId &&
|
|
389
|
+
ledger.lease.generation === args.generation;
|
|
390
|
+
return { head: ledger.head, leaseReleased: !stillOurs };
|
|
391
|
+
}
|
|
392
|
+
if (ledger.head !== args.expectedHead) {
|
|
393
|
+
throw new LedgerFencedError(
|
|
394
|
+
`commit(${sessionId}): head is ${ledger.head}, expected ${args.expectedHead}`
|
|
395
|
+
);
|
|
396
|
+
}
|
|
397
|
+
if (
|
|
398
|
+
ledger.lease === null ||
|
|
399
|
+
ledger.lease.holder !== this.podId ||
|
|
400
|
+
ledger.lease.generation !== args.generation
|
|
401
|
+
) {
|
|
402
|
+
throw new LedgerFencedError(
|
|
403
|
+
`commit(${sessionId}): lease generation ${args.generation} is stale`
|
|
404
|
+
);
|
|
405
|
+
}
|
|
406
|
+
const next: LedgerSnapshot = {
|
|
407
|
+
...ledger,
|
|
408
|
+
head: args.expectedHead + 1,
|
|
409
|
+
lease: null,
|
|
410
|
+
lastCommitId: args.commitId,
|
|
411
|
+
};
|
|
412
|
+
let result: Awaited<ReturnType<SessionLedgerKv["putIfVersion"]>>;
|
|
413
|
+
try {
|
|
414
|
+
result = await this.kv.putIfVersion(key, toJson(next), entry.version);
|
|
415
|
+
} catch {
|
|
416
|
+
// Unknown outcome — loop back to the re-read, which either finds
|
|
417
|
+
// our commitId (success) or a fresh version to CAS against.
|
|
418
|
+
await this.backoff(attempt);
|
|
419
|
+
continue;
|
|
420
|
+
}
|
|
421
|
+
if (result.ok) {
|
|
422
|
+
return { head: next.head, leaseReleased: true };
|
|
423
|
+
}
|
|
424
|
+
// Version conflict: a concurrent writer moved the record. Re-read
|
|
425
|
+
// and retry — the fencing predicates re-run against the fresh value.
|
|
426
|
+
await this.backoff(attempt);
|
|
427
|
+
}
|
|
428
|
+
throw new LedgerCasExhaustedError("commit", this.maxCasAttempts);
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* Release a held lease without committing — graceful shutdown, or a
|
|
433
|
+
* turn that failed before its commit. Fenced by generation: a stale
|
|
434
|
+
* holder's release is a no-op (the session has moved on). `head` and
|
|
435
|
+
* the acquisition counter are untouched, so prior holders stay fenced.
|
|
436
|
+
*/
|
|
437
|
+
async release(
|
|
438
|
+
sessionId: string,
|
|
439
|
+
generation: number
|
|
440
|
+
): Promise<{ released: boolean }> {
|
|
441
|
+
const key = this.ledgerKey(sessionId);
|
|
442
|
+
for (let attempt = 0; attempt < this.maxCasAttempts; attempt++) {
|
|
443
|
+
const entry = await this.kv.getWithVersion(key);
|
|
444
|
+
if (entry === undefined) {
|
|
445
|
+
return { released: false };
|
|
446
|
+
}
|
|
447
|
+
const ledger = parseLedgerSnapshot(entry.value);
|
|
448
|
+
if (
|
|
449
|
+
ledger.lease === null ||
|
|
450
|
+
ledger.lease.holder !== this.podId ||
|
|
451
|
+
ledger.lease.generation !== generation
|
|
452
|
+
) {
|
|
453
|
+
return { released: false };
|
|
454
|
+
}
|
|
455
|
+
const next: LedgerSnapshot = { ...ledger, lease: null };
|
|
456
|
+
const result = await this.kv.putIfVersion(
|
|
457
|
+
key,
|
|
458
|
+
toJson(next),
|
|
459
|
+
entry.version
|
|
460
|
+
);
|
|
461
|
+
if (result.ok) {
|
|
462
|
+
return { released: true };
|
|
463
|
+
}
|
|
464
|
+
await this.backoff(attempt);
|
|
465
|
+
}
|
|
466
|
+
throw new LedgerCasExhaustedError("release", this.maxCasAttempts);
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/** Parsed ledger value for one session, or `undefined` when never created. */
|
|
470
|
+
async readLedger(sessionId: string): Promise<LedgerSnapshot | undefined> {
|
|
471
|
+
const entry = await this.kv.getWithVersion(this.ledgerKey(sessionId));
|
|
472
|
+
return entry === undefined ? undefined : parseLedgerSnapshot(entry.value);
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
function toJson(value: SessionIdentity | LedgerSnapshot): JsonValue {
|
|
477
|
+
return value as unknown as JsonValue;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
function parseSessionIdentity(value: JsonValue): SessionIdentity {
|
|
481
|
+
const record = asRecord(value, "session identity");
|
|
482
|
+
const sessionId = record.sessionId;
|
|
483
|
+
const createdAt = record.createdAt;
|
|
484
|
+
if (typeof sessionId !== "string" || typeof createdAt !== "number") {
|
|
485
|
+
throw new Error("session ledger: malformed session identity value");
|
|
486
|
+
}
|
|
487
|
+
const sdkSessionRef = record.sdkSessionRef;
|
|
488
|
+
return {
|
|
489
|
+
sessionId,
|
|
490
|
+
sdkSessionRef: typeof sdkSessionRef === "string" ? sdkSessionRef : null,
|
|
491
|
+
createdAt,
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
function parseLedgerSnapshot(value: JsonValue): LedgerSnapshot {
|
|
496
|
+
const record = asRecord(value, "ledger");
|
|
497
|
+
const { sessionId, head, lease, generation, lastCommitId } = record;
|
|
498
|
+
if (
|
|
499
|
+
typeof sessionId !== "string" ||
|
|
500
|
+
typeof head !== "number" ||
|
|
501
|
+
typeof generation !== "number"
|
|
502
|
+
) {
|
|
503
|
+
throw new Error("session ledger: malformed ledger value");
|
|
504
|
+
}
|
|
505
|
+
return {
|
|
506
|
+
sessionId,
|
|
507
|
+
head,
|
|
508
|
+
lease: parseLease(lease),
|
|
509
|
+
generation,
|
|
510
|
+
lastCommitId: typeof lastCommitId === "string" ? lastCommitId : null,
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
function parseLease(value: JsonValue | undefined): LedgerLease | null {
|
|
515
|
+
if (value === null || value === undefined) {
|
|
516
|
+
return null;
|
|
517
|
+
}
|
|
518
|
+
const record = asRecord(value, "lease");
|
|
519
|
+
const { holder, generation, expiresAt } = record;
|
|
520
|
+
if (
|
|
521
|
+
typeof holder !== "string" ||
|
|
522
|
+
typeof generation !== "number" ||
|
|
523
|
+
typeof expiresAt !== "number"
|
|
524
|
+
) {
|
|
525
|
+
throw new Error("session ledger: malformed lease value");
|
|
526
|
+
}
|
|
527
|
+
return { holder, generation, expiresAt };
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
function asRecord(value: JsonValue, what: string): JsonObject {
|
|
531
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
532
|
+
throw new Error(`session ledger: ${what} value is not an object`);
|
|
533
|
+
}
|
|
534
|
+
return value;
|
|
535
|
+
}
|
package/src/ledger.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session ledger — coordination only. The protocol library that drives
|
|
3
|
+
* the `session/` and `ledger/` key families over a CAS-capable KV:
|
|
4
|
+
* identity creation, lease claim/heartbeat/release, and the fenced
|
|
5
|
+
* commit sequence. The durable inbox (pending events, mailbox payloads,
|
|
6
|
+
* append/drain, the janitor) lands in a follow-up; see
|
|
7
|
+
* `src/ledger/session-ledger.ts` for the trade-off this stage accepts.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export type {
|
|
11
|
+
ClaimResult,
|
|
12
|
+
CommitArgs,
|
|
13
|
+
CommitResult,
|
|
14
|
+
EnsureSessionResult,
|
|
15
|
+
HeartbeatResult,
|
|
16
|
+
LedgerLease,
|
|
17
|
+
LedgerSnapshot,
|
|
18
|
+
SessionIdentity,
|
|
19
|
+
SessionLedgerKv,
|
|
20
|
+
SessionLedgerOptions,
|
|
21
|
+
} from "./ledger/session-ledger.js";
|
|
22
|
+
export {
|
|
23
|
+
HEARTBEAT_INTERVAL_MS,
|
|
24
|
+
LEASE_TTL_MS,
|
|
25
|
+
LedgerCasExhaustedError,
|
|
26
|
+
LedgerFencedError,
|
|
27
|
+
SessionLedger,
|
|
28
|
+
supportsSessionLedgerKv,
|
|
29
|
+
} from "./ledger/session-ledger.js";
|