@loomwork/conversation 0.0.0-stage → 0.1.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.
Files changed (83) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +8 -0
  3. package/README.md +117 -2
  4. package/dist/access.d.ts +59 -0
  5. package/dist/access.d.ts.map +1 -0
  6. package/dist/access.js +178 -0
  7. package/dist/access.js.map +1 -0
  8. package/dist/bargeIn.d.ts +62 -0
  9. package/dist/bargeIn.d.ts.map +1 -0
  10. package/dist/bargeIn.js +110 -0
  11. package/dist/bargeIn.js.map +1 -0
  12. package/dist/budget.d.ts +82 -0
  13. package/dist/budget.d.ts.map +1 -0
  14. package/dist/budget.js +134 -0
  15. package/dist/budget.js.map +1 -0
  16. package/dist/conversation.d.ts +59 -0
  17. package/dist/conversation.d.ts.map +1 -0
  18. package/dist/conversation.js +786 -0
  19. package/dist/conversation.js.map +1 -0
  20. package/dist/conversations.d.ts +149 -0
  21. package/dist/conversations.d.ts.map +1 -0
  22. package/dist/conversations.js +498 -0
  23. package/dist/conversations.js.map +1 -0
  24. package/dist/feed.d.ts +32 -0
  25. package/dist/feed.d.ts.map +1 -0
  26. package/dist/feed.js +83 -0
  27. package/dist/feed.js.map +1 -0
  28. package/dist/hub.d.ts +119 -0
  29. package/dist/hub.d.ts.map +1 -0
  30. package/dist/hub.js +257 -0
  31. package/dist/hub.js.map +1 -0
  32. package/dist/ids.d.ts +9 -0
  33. package/dist/ids.d.ts.map +1 -0
  34. package/dist/ids.js +29 -0
  35. package/dist/ids.js.map +1 -0
  36. package/dist/index.d.ts +27 -0
  37. package/dist/index.d.ts.map +1 -0
  38. package/dist/index.js +65 -0
  39. package/dist/index.js.map +1 -0
  40. package/dist/providerError.d.ts +10 -0
  41. package/dist/providerError.d.ts.map +1 -0
  42. package/dist/providerError.js +16 -0
  43. package/dist/providerError.js.map +1 -0
  44. package/dist/reader.d.ts +53 -0
  45. package/dist/reader.d.ts.map +1 -0
  46. package/dist/reader.js +217 -0
  47. package/dist/reader.js.map +1 -0
  48. package/dist/settled.d.ts +49 -0
  49. package/dist/settled.d.ts.map +1 -0
  50. package/dist/settled.js +51 -0
  51. package/dist/settled.js.map +1 -0
  52. package/dist/signEnvelope.d.ts +51 -0
  53. package/dist/signEnvelope.d.ts.map +1 -0
  54. package/dist/signEnvelope.js +55 -0
  55. package/dist/signEnvelope.js.map +1 -0
  56. package/dist/summarizerText.d.ts +2 -0
  57. package/dist/summarizerText.d.ts.map +1 -0
  58. package/dist/summarizerText.js +9 -0
  59. package/dist/summarizerText.js.map +1 -0
  60. package/dist/turn.d.ts +67 -0
  61. package/dist/turn.d.ts.map +1 -0
  62. package/dist/turn.js +213 -0
  63. package/dist/turn.js.map +1 -0
  64. package/dist/types.d.ts +267 -0
  65. package/dist/types.d.ts.map +1 -0
  66. package/dist/types.js +18 -0
  67. package/dist/types.js.map +1 -0
  68. package/package.json +61 -3
  69. package/src/access.ts +221 -0
  70. package/src/bargeIn.ts +172 -0
  71. package/src/budget.ts +170 -0
  72. package/src/conversation.ts +961 -0
  73. package/src/conversations.ts +690 -0
  74. package/src/feed.ts +112 -0
  75. package/src/hub.ts +336 -0
  76. package/src/ids.ts +25 -0
  77. package/src/index.ts +75 -0
  78. package/src/reader.ts +274 -0
  79. package/src/settled.ts +80 -0
  80. package/src/signEnvelope.ts +76 -0
  81. package/src/summarizerText.ts +3 -0
  82. package/src/turn.ts +344 -0
  83. package/src/types.ts +271 -0
@@ -0,0 +1,62 @@
1
+ import { type EventStore } from "@loomwork/event-runtime";
2
+ export interface BargeInHandlers {
3
+ /** Fire the running turn's abort signal. */
4
+ onMessage: () => void;
5
+ /** Whether a client idempotency key belongs to a turn this conversation already took (or is running). */
6
+ isKnown: (id: string) => boolean;
7
+ /**
8
+ * Whether a stored inbox message may interrupt the running turn at all. Default: any message on the
9
+ * conversation topic. Shared mode passes a check that the envelope is signed AND from the SAME asker
10
+ * as the running turn: a participant interrupts only their own turn.
11
+ */
12
+ accept?: (stored: StoredInboxMessage) => boolean;
13
+ /**
14
+ * The idempotency key a stored message claims. Default (owner mode): the payload `id`, honoured only
15
+ * when it equals the kernel's dedupe identity of THIS message (`senderKey(sender, messageId)`), so a
16
+ * different sender replaying someone's id is a new message, not a retry.
17
+ */
18
+ idOf?: (stored: StoredInboxMessage) => string | undefined;
19
+ }
20
+ /** What the inbox stream holds per message (the shape `runtime.send` appends). */
21
+ export interface StoredInboxMessage {
22
+ topic?: unknown;
23
+ messageId?: unknown;
24
+ payload?: unknown;
25
+ sender?: {
26
+ tenant?: string;
27
+ actor?: string;
28
+ onBehalfOf?: string;
29
+ };
30
+ }
31
+ /**
32
+ * Tell `handlers.onMessage` when a NEW message lands for `conversationId`, and return the way to stop
33
+ * listening. `ownerId` is the execution (generation) running the turn. Supplied to
34
+ * `ConversationConfig.bargeIn`; the standard source is {@link inboxBargeIn}. Without one a
35
+ * conversation QUEUES: a message sent mid-turn waits for the turn to finish.
36
+ */
37
+ export type BargeInSource = (conversationId: string, ownerId: string, handlers: BargeInHandlers) => Promise<() => void> | (() => void);
38
+ /** Whether `m` is a NEW message by the handlers' rules (on the topic, accepted, not a known retry). */
39
+ export declare function isNew(m: StoredInboxMessage, h: Pick<BargeInHandlers, "isKnown" | "accept" | "idOf">): boolean;
40
+ /**
41
+ * Whether the inbox holds a message the owner has not consumed and the conversation does not already
42
+ * know: the stream past the newest `MESSAGE_CONSUMED` cursor in the owner's log. The owner's log is read
43
+ * BACKWARDS in blocks until a consumption is found (bounded by {@link MAX_LOOKBACK} events), so a turn
44
+ * with any amount of tool traffic, or a recovery re-running one, is still compared against the right
45
+ * cursor. Conservative: when no consumption is found (a fresh generation whose first message rode the
46
+ * carry) it says `false` and the message is simply handled after the turn.
47
+ */
48
+ export declare function pendingInbox(store: EventStore, conversationId: string, ownerId: string, h?: Pick<BargeInHandlers, "isKnown" | "accept" | "idOf">): Promise<boolean>;
49
+ /**
50
+ * The messages waiting in the inbox past the owner's consumed cursor (at most `limit`), or `undefined`
51
+ * when the cursor cannot be established. The owner's log is read BACKWARDS in blocks until a consumption
52
+ * is found, bounded by {@link MAX_LOOKBACK}.
53
+ */
54
+ export declare function pendingMessages(store: EventStore, conversationId: string, ownerId: string, limit: number): Promise<StoredInboxMessage[] | undefined>;
55
+ /**
56
+ * The standard {@link BargeInSource}: subscribe to the conversation's inbox stream on `eventStore`
57
+ * (an in-process notification for the in-memory store, LISTEN/NOTIFY for Postgres), and, once
58
+ * subscribed, look for a message that is ALREADY waiting (one sent between the previous turn's
59
+ * consumption and now), so a message cannot be missed by arriving a moment early.
60
+ */
61
+ export declare function inboxBargeIn(eventStore: EventStore): BargeInSource;
62
+ //# sourceMappingURL=bargeIn.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bargeIn.d.ts","sourceRoot":"","sources":["../src/bargeIn.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,UAAU,EAAuB,MAAM,yBAAyB,CAAC;AAwB/E,MAAM,WAAW,eAAe;IAC9B,4CAA4C;IAC5C,SAAS,EAAE,MAAM,IAAI,CAAC;IACtB,yGAAyG;IACzG,OAAO,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,OAAO,CAAC;IACjC;;;;OAIG;IACH,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,kBAAkB,KAAK,OAAO,CAAC;IACjD;;;;OAIG;IACH,IAAI,CAAC,EAAE,CAAC,MAAM,EAAE,kBAAkB,KAAK,MAAM,GAAG,SAAS,CAAC;CAC3D;AAED,kFAAkF;AAClF,MAAM,WAAW,kBAAkB;IACjC,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,MAAM,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CACnE;AAED;;;;;GAKG;AACH,MAAM,MAAM,aAAa,GAAG,CAC1B,cAAc,EAAE,MAAM,EACtB,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,eAAe,KACtB,OAAO,CAAC,MAAM,IAAI,CAAC,GAAG,CAAC,MAAM,IAAI,CAAC,CAAC;AAcxC,uGAAuG;AACvG,wBAAgB,KAAK,CACnB,CAAC,EAAE,kBAAkB,EACrB,CAAC,EAAE,IAAI,CAAC,eAAe,EAAE,SAAS,GAAG,QAAQ,GAAG,MAAM,CAAC,GACtD,OAAO,CAKT;AAED;;;;;;;GAOG;AACH,wBAAsB,YAAY,CAChC,KAAK,EAAE,UAAU,EACjB,cAAc,EAAE,MAAM,EACtB,OAAO,EAAE,MAAM,EACf,CAAC,GAAE,IAAI,CAAC,eAAe,EAAE,SAAS,GAAG,QAAQ,GAAG,MAAM,CAA4B,GACjF,OAAO,CAAC,OAAO,CAAC,CAGlB;AAED;;;;GAIG;AACH,wBAAsB,eAAe,CACnC,KAAK,EAAE,UAAU,EACjB,cAAc,EAAE,MAAM,EACtB,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC,kBAAkB,EAAE,GAAG,SAAS,CAAC,CAwB3C;AAED;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,UAAU,EAAE,UAAU,GAAG,aAAa,CAwBlE"}
@@ -0,0 +1,110 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isNew = isNew;
4
+ exports.pendingInbox = pendingInbox;
5
+ exports.pendingMessages = pendingMessages;
6
+ exports.inboxBargeIn = inboxBargeIn;
7
+ const event_runtime_1 = require("@loomwork/event-runtime");
8
+ const workflow_runtime_1 = require("@loomwork/workflow-runtime");
9
+ const access_1 = require("./access");
10
+ const types_1 = require("./types");
11
+ /** How far back in the owner's log the consumed cursor is looked for, at most. */
12
+ const MAX_LOOKBACK = 8192;
13
+ const TAIL_BLOCK = 128;
14
+ /** How many waiting messages a peek inspects. */
15
+ const PEEK_LIMIT = 16;
16
+ const ownerModeId = (m) => {
17
+ const id = m.payload?.id;
18
+ if (typeof id !== "string" || typeof m.messageId !== "string")
19
+ return undefined;
20
+ return id === (0, access_1.senderKey)(m.sender ?? {}, m.messageId) ? id : undefined;
21
+ };
22
+ /** Whether `m` is a NEW message by the handlers' rules (on the topic, accepted, not a known retry). */
23
+ function isNew(m, h) {
24
+ if (m.topic !== types_1.CONVERSATION_TOPIC)
25
+ return false;
26
+ if (h.accept !== undefined && !h.accept(m))
27
+ return false;
28
+ const id = (h.idOf ?? ownerModeId)(m);
29
+ return id === undefined || !h.isKnown(id);
30
+ }
31
+ /**
32
+ * Whether the inbox holds a message the owner has not consumed and the conversation does not already
33
+ * know: the stream past the newest `MESSAGE_CONSUMED` cursor in the owner's log. The owner's log is read
34
+ * BACKWARDS in blocks until a consumption is found (bounded by {@link MAX_LOOKBACK} events), so a turn
35
+ * with any amount of tool traffic, or a recovery re-running one, is still compared against the right
36
+ * cursor. Conservative: when no consumption is found (a fresh generation whose first message rode the
37
+ * carry) it says `false` and the message is simply handled after the turn.
38
+ */
39
+ async function pendingInbox(store, conversationId, ownerId, h = { isKnown: () => false }) {
40
+ const waiting = await pendingMessages(store, conversationId, ownerId, PEEK_LIMIT);
41
+ return waiting?.some((m) => isNew(m, h)) === true;
42
+ }
43
+ /**
44
+ * The messages waiting in the inbox past the owner's consumed cursor (at most `limit`), or `undefined`
45
+ * when the cursor cannot be established. The owner's log is read BACKWARDS in blocks until a consumption
46
+ * is found, bounded by {@link MAX_LOOKBACK}.
47
+ */
48
+ async function pendingMessages(store, conversationId, ownerId, limit) {
49
+ // The conversation topic's messages live in the legacy stream or, once the fleet writes per-topic
50
+ // streams (ADR 0110 D10b), in the topic's own; the cursor is one number space across both.
51
+ const legacyHead = await (0, event_runtime_1.headOf)(store, (0, workflow_runtime_1.inboxStreamId)(conversationId));
52
+ const topicHead = await (0, event_runtime_1.headOf)(store, (0, workflow_runtime_1.inboxTopicStreamId)(conversationId, types_1.CONVERSATION_TOPIC));
53
+ if (legacyHead === null && topicHead === null)
54
+ return [];
55
+ const newest = Math.max(legacyHead ?? -1, topicHead ?? -1);
56
+ const tip = await (0, event_runtime_1.headOf)(store, ownerId);
57
+ if (tip === null)
58
+ return undefined;
59
+ let consumed = -1;
60
+ let upper = tip;
61
+ while (upper >= 0 && tip - upper < MAX_LOOKBACK && consumed < 0) {
62
+ const lo = Math.max(0, upper - TAIL_BLOCK + 1);
63
+ const block = await (0, event_runtime_1.readRangeOf)(store, ownerId, lo, upper);
64
+ for (const ev of block) {
65
+ if (ev.eventType !== "MESSAGE_CONSUMED")
66
+ continue;
67
+ const seq = ev.payload?.inboxSeq;
68
+ if (typeof seq === "number" && seq > consumed)
69
+ consumed = seq;
70
+ }
71
+ upper = lo - 1;
72
+ }
73
+ if (consumed < 0)
74
+ return undefined;
75
+ if (newest <= consumed)
76
+ return [];
77
+ return (0, workflow_runtime_1.createInboxSource)(store)(conversationId, types_1.CONVERSATION_TOPIC, consumed, limit);
78
+ }
79
+ /**
80
+ * The standard {@link BargeInSource}: subscribe to the conversation's inbox stream on `eventStore`
81
+ * (an in-process notification for the in-memory store, LISTEN/NOTIFY for Postgres), and, once
82
+ * subscribed, look for a message that is ALREADY waiting (one sent between the previous turn's
83
+ * consumption and now), so a message cannot be missed by arriving a moment early.
84
+ */
85
+ function inboxBargeIn(eventStore) {
86
+ return async (conversationId, ownerId, handlers) => {
87
+ const onEvent = (ev) => {
88
+ if (isNew(ev.payload, handlers))
89
+ handlers.onMessage();
90
+ };
91
+ // Both layouts (ADR 0110 D10b): a message lands in the legacy stream or in the topic's own.
92
+ const unsubLegacy = await eventStore.subscribe((0, workflow_runtime_1.inboxStreamId)(conversationId), onEvent);
93
+ let unsubTopic;
94
+ const unsubscribe = () => {
95
+ unsubLegacy();
96
+ unsubTopic?.();
97
+ };
98
+ try {
99
+ unsubTopic = await eventStore.subscribe((0, workflow_runtime_1.inboxTopicStreamId)(conversationId, types_1.CONVERSATION_TOPIC), onEvent);
100
+ if (await pendingInbox(eventStore, conversationId, ownerId, handlers))
101
+ handlers.onMessage();
102
+ }
103
+ catch (err) {
104
+ unsubscribe();
105
+ throw err;
106
+ }
107
+ return unsubscribe;
108
+ };
109
+ }
110
+ //# sourceMappingURL=bargeIn.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bargeIn.js","sourceRoot":"","sources":["../src/bargeIn.ts"],"names":[],"mappings":";;AA6EA,sBAQC;AAUD,oCAQC;AAOD,0CA6BC;AAQD,oCAwBC;AA1KD,2DAA+E;AAC/E,iEAAkG;AAClG,qCAAqC;AACrC,mCAA6C;AA4D7C,kFAAkF;AAClF,MAAM,YAAY,GAAG,IAAI,CAAC;AAC1B,MAAM,UAAU,GAAG,GAAG,CAAC;AACvB,iDAAiD;AACjD,MAAM,UAAU,GAAG,EAAE,CAAC;AAEtB,MAAM,WAAW,GAAG,CAAC,CAAqB,EAAsB,EAAE;IAChE,MAAM,EAAE,GAAI,CAAC,CAAC,OAA+C,EAAE,EAAE,CAAC;IAClE,IAAI,OAAO,EAAE,KAAK,QAAQ,IAAI,OAAO,CAAC,CAAC,SAAS,KAAK,QAAQ;QAAE,OAAO,SAAS,CAAC;IAChF,OAAO,EAAE,KAAK,IAAA,kBAAS,EAAC,CAAC,CAAC,MAAM,IAAI,EAAE,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;AACxE,CAAC,CAAC;AAEF,uGAAuG;AACvG,SAAgB,KAAK,CACnB,CAAqB,EACrB,CAAuD;IAEvD,IAAI,CAAC,CAAC,KAAK,KAAK,0BAAkB;QAAE,OAAO,KAAK,CAAC;IACjD,IAAI,CAAC,CAAC,MAAM,KAAK,SAAS,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;QAAE,OAAO,KAAK,CAAC;IACzD,MAAM,EAAE,GAAG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5F,MAAM,WAAW,GAAG,MAAM,UAAU,CAAC,SAAS,CAAC,IAAA,gCAAa,EAAC,cAAc,CAAC,EAAE,OAAO,CAAC,CAAC;QACvF,IAAI,UAAoC,CAAC;QACzC,MAAM,WAAW,GAAG,GAAS,EAAE;YAC7B,WAAW,EAAE,CAAC;YACd,UAAU,EAAE,EAAE,CAAC;QACjB,CAAC,CAAC;QACF,IAAI,CAAC;YACH,UAAU,GAAG,MAAM,UAAU,CAAC,SAAS,CACrC,IAAA,qCAAkB,EAAC,cAAc,EAAE,0BAAkB,CAAC,EACtD,OAAO,CACR,CAAC;YACF,IAAI,MAAM,YAAY,CAAC,UAAU,EAAE,cAAc,EAAE,OAAO,EAAE,QAAQ,CAAC;gBAAE,QAAQ,CAAC,SAAS,EAAE,CAAC;QAC9F,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,WAAW,EAAE,CAAC;YACd,MAAM,GAAG,CAAC;QACZ,CAAC;QACD,OAAO,WAAW,CAAC;IACrB,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,82 @@
1
+ /** Counts the tokens of a text. Sync or async; a provider may supply its exact tokenizer. */
2
+ export interface TokenCounter {
3
+ count(text: string): number | Promise<number>;
4
+ /** Tokens a single message costs beyond its text (role markers, separators). Default 4. */
5
+ readonly perMessage?: number;
6
+ }
7
+ /**
8
+ * The default counter: no tokenizer, no dependency, deterministic and CONSERVATIVE. ASCII costs a
9
+ * quarter token per character (the usual English rule of thumb, rounded UP), every other code point
10
+ * costs a whole token (CJK, emoji and symbols tokenize at roughly one token or more per character,
11
+ * so a flat chars/4 would under-count them by 4x and overflow the window). Over-counting only costs
12
+ * some history; under-counting costs the request.
13
+ */
14
+ export declare function heuristicTokenCounter(options?: {
15
+ asciiCharsPerToken?: number;
16
+ }): TokenCounter;
17
+ export declare class ContextBudgetError extends Error {
18
+ readonly code = "CONTEXT_BUDGET";
19
+ constructor(message: string);
20
+ }
21
+ /** One turn of the history the budgeter weighs: its token cost is counted once and cached. */
22
+ export interface BudgetTurn {
23
+ /** The tokens of the turn's messages (user + assistant), if already counted. */
24
+ tokens?: number;
25
+ user: string;
26
+ assistant?: string;
27
+ }
28
+ export interface BudgetRequest {
29
+ /** The model's context window, in tokens. */
30
+ contextWindow: number;
31
+ /** Tokens held back for the reply. Default `min(4096, window / 4)`. */
32
+ reserveOutputTokens?: number;
33
+ /** The system prompt (counted once). */
34
+ system?: string;
35
+ /** The rolling summary of evicted turns (counted once), if any. */
36
+ summary?: string;
37
+ /** The new user message. */
38
+ prompt: string;
39
+ /** Turns oldest first. */
40
+ turns: readonly BudgetTurn[];
41
+ counter?: TokenCounter;
42
+ }
43
+ export type BudgetVerdict = {
44
+ ok: true;
45
+ /** How many of the NEWEST turns fit (the rest are to be dropped / summarized). */
46
+ keep: number;
47
+ /** Tokens counted for each turn that had none: `[index, tokens]`. */
48
+ counted: [number, number][];
49
+ /** The total the request will cost (fixed parts + kept turns), reply reserve excluded. */
50
+ tokens: number;
51
+ /** The rolling summary alone made the request not fit, so it was left out of this fit (and is to be dropped). */
52
+ dropSummary?: true;
53
+ } | {
54
+ ok: false;
55
+ reason: "prompt-too-large";
56
+ tokens: number;
57
+ available: number;
58
+ };
59
+ /**
60
+ * Fit `system + summary + turns + prompt` into `contextWindow - reserveOutputTokens`. Keeps the
61
+ * longest NEWEST suffix of whole turns that fits (a turn is never split); the prompt is never
62
+ * dropped, and when system + summary + prompt alone exceed the window the verdict is
63
+ * `prompt-too-large` (the caller refuses the turn rather than send a request the provider will
64
+ * reject). Pure of the counter's answers: the same counts give the same verdict.
65
+ *
66
+ * Cost: one `count` per turn that has no cached `tokens`, then a single backwards pass; the caller
67
+ * caches `counted` on its turns, so a steady-state conversation counts only the NEW turn per call.
68
+ */
69
+ export declare function fitToWindow(req: BudgetRequest): Promise<BudgetVerdict>;
70
+ /**
71
+ * `fitToWindow`, but a rolling summary that is itself too big to leave room for the prompt is DROPPED
72
+ * rather than wedging the conversation: with no summary the same request may fit. The verdict says so
73
+ * (`dropSummary`) and the caller discards the summary. Still `prompt-too-large` when it cannot fit even so.
74
+ */
75
+ export declare function fitWithSummaryFallback(req: BudgetRequest): Promise<BudgetVerdict>;
76
+ /**
77
+ * The longest prefix of `text` that costs at most `maxTokens`, with an ellipsis when cut: a binary
78
+ * search over prefix lengths, O(log n) counts. Deterministic for a deterministic counter, and the
79
+ * caller records its answer anyway.
80
+ */
81
+ export declare function truncateToTokens(text: string, maxTokens: number, counter: TokenCounter): Promise<string>;
82
+ //# sourceMappingURL=budget.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"budget.d.ts","sourceRoot":"","sources":["../src/budget.ts"],"names":[],"mappings":"AASA,6FAA6F;AAC7F,MAAM,WAAW,YAAY;IAC3B,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAC9C,2FAA2F;IAC3F,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;CAC9B;AAED;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,GAAE;IAAE,kBAAkB,CAAC,EAAE,MAAM,CAAA;CAAO,GAAG,YAAY,CAiBjG;AAED,qBAAa,kBAAmB,SAAQ,KAAK;IAC3C,QAAQ,CAAC,IAAI,oBAAoB;gBACrB,OAAO,EAAE,MAAM;CAI5B;AAED,8FAA8F;AAC9F,MAAM,WAAW,UAAU;IACzB,gFAAgF;IAChF,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,aAAa;IAC5B,6CAA6C;IAC7C,aAAa,EAAE,MAAM,CAAC;IACtB,uEAAuE;IACvE,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,wCAAwC;IACxC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,mEAAmE;IACnE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,4BAA4B;IAC5B,MAAM,EAAE,MAAM,CAAC;IACf,0BAA0B;IAC1B,KAAK,EAAE,SAAS,UAAU,EAAE,CAAC;IAC7B,OAAO,CAAC,EAAE,YAAY,CAAC;CACxB;AAED,MAAM,MAAM,aAAa,GACrB;IACE,EAAE,EAAE,IAAI,CAAC;IACT,kFAAkF;IAClF,IAAI,EAAE,MAAM,CAAC;IACb,qEAAqE;IACrE,OAAO,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,CAAC;IAC5B,0FAA0F;IAC1F,MAAM,EAAE,MAAM,CAAC;IACf,iHAAiH;IACjH,WAAW,CAAC,EAAE,IAAI,CAAC;CACpB,GACD;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,kBAAkB,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,CAAC;AAEjF;;;;;;;;;GASG;AACH,wBAAsB,WAAW,CAAC,GAAG,EAAE,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC,CAqC5E;AAED;;;;GAIG;AACH,wBAAsB,sBAAsB,CAAC,GAAG,EAAE,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC,CAMvF;AAED;;;;GAIG;AACH,wBAAsB,gBAAgB,CACpC,IAAI,EAAE,MAAM,EACZ,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE,YAAY,GACpB,OAAO,CAAC,MAAM,CAAC,CAUjB"}
package/dist/budget.js ADDED
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+ // ── Token-aware context budgeting (ADR 0122 D3) ───────────────────────────────────────────────
3
+ //
4
+ // `agentLoop$`'s `compaction` triggers on message COUNT and UTF-8 BYTES, never on tokens, and it
5
+ // folds the transcript of ONE run. A dialogue outlives a run: the question here is "which of the
6
+ // turns I hold fit the model's window beside the system prompt and the new message", asked once per
7
+ // user turn. This module answers it as a PURE function over counted tokens, so the only
8
+ // non-deterministic ingredient (a provider's exact counter) is isolated behind a seam the caller
9
+ // records (`conversation$` journals the verdict as a decision; a replay never calls the counter).
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.ContextBudgetError = void 0;
12
+ exports.heuristicTokenCounter = heuristicTokenCounter;
13
+ exports.fitToWindow = fitToWindow;
14
+ exports.fitWithSummaryFallback = fitWithSummaryFallback;
15
+ exports.truncateToTokens = truncateToTokens;
16
+ /**
17
+ * The default counter: no tokenizer, no dependency, deterministic and CONSERVATIVE. ASCII costs a
18
+ * quarter token per character (the usual English rule of thumb, rounded UP), every other code point
19
+ * costs a whole token (CJK, emoji and symbols tokenize at roughly one token or more per character,
20
+ * so a flat chars/4 would under-count them by 4x and overflow the window). Over-counting only costs
21
+ * some history; under-counting costs the request.
22
+ */
23
+ function heuristicTokenCounter(options = {}) {
24
+ const per = options.asciiCharsPerToken ?? 4;
25
+ if (!(per >= 1) || !Number.isFinite(per)) {
26
+ throw new RangeError("heuristicTokenCounter: asciiCharsPerToken must be a number >= 1");
27
+ }
28
+ return {
29
+ perMessage: 4,
30
+ count(text) {
31
+ let ascii = 0;
32
+ let wide = 0;
33
+ for (const ch of text) {
34
+ if (ch.codePointAt(0) < 0x80)
35
+ ascii++;
36
+ else
37
+ wide++;
38
+ }
39
+ return Math.ceil(ascii / per) + wide;
40
+ },
41
+ };
42
+ }
43
+ class ContextBudgetError extends Error {
44
+ code = "CONTEXT_BUDGET";
45
+ constructor(message) {
46
+ super(message);
47
+ this.name = "ContextBudgetError";
48
+ }
49
+ }
50
+ exports.ContextBudgetError = ContextBudgetError;
51
+ /**
52
+ * Fit `system + summary + turns + prompt` into `contextWindow - reserveOutputTokens`. Keeps the
53
+ * longest NEWEST suffix of whole turns that fits (a turn is never split); the prompt is never
54
+ * dropped, and when system + summary + prompt alone exceed the window the verdict is
55
+ * `prompt-too-large` (the caller refuses the turn rather than send a request the provider will
56
+ * reject). Pure of the counter's answers: the same counts give the same verdict.
57
+ *
58
+ * Cost: one `count` per turn that has no cached `tokens`, then a single backwards pass; the caller
59
+ * caches `counted` on its turns, so a steady-state conversation counts only the NEW turn per call.
60
+ */
61
+ async function fitToWindow(req) {
62
+ const counter = req.counter ?? heuristicTokenCounter();
63
+ const overhead = counter.perMessage ?? 4;
64
+ if (!Number.isFinite(req.contextWindow) || req.contextWindow <= 0) {
65
+ throw new RangeError("fitToWindow: contextWindow must be a positive number");
66
+ }
67
+ const reserve = req.reserveOutputTokens ?? Math.min(4096, Math.floor(req.contextWindow / 4));
68
+ const available = req.contextWindow - reserve;
69
+ let fixed = overhead; // the prompt message
70
+ fixed += await counter.count(req.prompt);
71
+ if (req.system !== undefined && req.system !== "")
72
+ fixed += await counter.count(req.system);
73
+ if (req.summary !== undefined && req.summary !== "") {
74
+ fixed += overhead + (await counter.count(req.summary));
75
+ }
76
+ if (fixed > available)
77
+ return { ok: false, reason: "prompt-too-large", tokens: fixed, available };
78
+ const counted = [];
79
+ const weights = new Array(req.turns.length);
80
+ // Walk newest -> oldest and stop at the first turn that does not fit: older turns are never
81
+ // counted, so a long window costs O(kept), not O(held).
82
+ let used = fixed;
83
+ let keep = 0;
84
+ for (let i = req.turns.length - 1; i >= 0; i--) {
85
+ const turn = req.turns[i];
86
+ let w = turn.tokens;
87
+ if (w === undefined) {
88
+ w = overhead + (await counter.count(turn.user));
89
+ if (turn.assistant !== undefined && turn.assistant !== "") {
90
+ w += overhead + (await counter.count(turn.assistant));
91
+ }
92
+ counted.push([i, w]);
93
+ }
94
+ weights[i] = w;
95
+ if (used + w > available)
96
+ break;
97
+ used += w;
98
+ keep++;
99
+ }
100
+ return { ok: true, keep, counted, tokens: used };
101
+ }
102
+ /**
103
+ * `fitToWindow`, but a rolling summary that is itself too big to leave room for the prompt is DROPPED
104
+ * rather than wedging the conversation: with no summary the same request may fit. The verdict says so
105
+ * (`dropSummary`) and the caller discards the summary. Still `prompt-too-large` when it cannot fit even so.
106
+ */
107
+ async function fitWithSummaryFallback(req) {
108
+ const v = await fitToWindow(req);
109
+ if (v.ok || req.summary === undefined || req.summary === "")
110
+ return v;
111
+ const { summary: _dropped, ...rest } = req;
112
+ const again = await fitToWindow(rest);
113
+ return again.ok ? { ...again, dropSummary: true } : again;
114
+ }
115
+ /**
116
+ * The longest prefix of `text` that costs at most `maxTokens`, with an ellipsis when cut: a binary
117
+ * search over prefix lengths, O(log n) counts. Deterministic for a deterministic counter, and the
118
+ * caller records its answer anyway.
119
+ */
120
+ async function truncateToTokens(text, maxTokens, counter) {
121
+ if ((await counter.count(text)) <= maxTokens)
122
+ return text;
123
+ let lo = 0;
124
+ let hi = text.length;
125
+ while (lo < hi) {
126
+ const mid = Math.ceil((lo + hi) / 2);
127
+ if ((await counter.count(text.slice(0, mid))) <= maxTokens)
128
+ lo = mid;
129
+ else
130
+ hi = mid - 1;
131
+ }
132
+ return lo === 0 ? "" : `${text.slice(0, lo)}…`;
133
+ }
134
+ //# sourceMappingURL=budget.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"budget.js","sourceRoot":"","sources":["../src/budget.ts"],"names":[],"mappings":";AAAA,iGAAiG;AACjG,EAAE;AACF,iGAAiG;AACjG,iGAAiG;AACjG,oGAAoG;AACpG,wFAAwF;AACxF,iGAAiG;AACjG,kGAAkG;;;AAgBlG,sDAiBC;AA0DD,kCAqCC;AAOD,wDAMC;AAOD,4CAcC;AAzJD;;;;;;GAMG;AACH,SAAgB,qBAAqB,CAAC,UAA2C,EAAE;IACjF,MAAM,GAAG,GAAG,OAAO,CAAC,kBAAkB,IAAI,CAAC,CAAC;IAC5C,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QACzC,MAAM,IAAI,UAAU,CAAC,iEAAiE,CAAC,CAAC;IAC1F,CAAC;IACD,OAAO;QACL,UAAU,EAAE,CAAC;QACb,KAAK,CAAC,IAAY;YAChB,IAAI,KAAK,GAAG,CAAC,CAAC;YACd,IAAI,IAAI,GAAG,CAAC,CA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AAC;QACf,MAAM,GAAG,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;QACrC,IAAI,CAAC,MAAM,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,IAAI,SAAS;YAAE,EAAE,GAAG,GAAG,CAAC;;YAChE,EAAE,GAAG,GAAG,GAAG,CAAC,CAAC;IACpB,CAAC;IACD,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC;AACjD,CAAC"}
@@ -0,0 +1,59 @@
1
+ import type { FlowRunner, RegisteredFlow } from "@loomwork/workflow-runtime";
2
+ import { type TurnInput, type TurnResult, registerSharedTurnEffect, sharedTurnEffect } from "./turn";
3
+ import { type ConversationCarry, type ConversationConfig, type ConversationResult, type TurnEnvelope } from "./types";
4
+ export type EnvelopeRefusal = "malformed" | "unauthenticated";
5
+ /**
6
+ * Both modes: an envelope is acted on only if the host's client SIGNED it, for THIS conversation, with an
7
+ * issue time and an id (the replay set's key). The signature covers every field, so none can be lifted
8
+ * from one message into another.
9
+ */
10
+ export declare function parseSignedEnvelope(value: unknown, keys: string | readonly string[], conversationId: string): {
11
+ env?: TurnEnvelope;
12
+ reason?: EnvelopeRefusal;
13
+ };
14
+ /** What the client signs / the body checks (the envelope without its signature). */
15
+ export declare function signedEnvelope(key: string, body: Record<string, unknown>): Record<string, unknown>;
16
+ /**
17
+ * The start input is the owner's, but it is read like any untrusted JSON: shape, counts and bytes are
18
+ * all bounded here, so a malformed or oversized input can neither crash the body nor inflate the window.
19
+ */
20
+ export declare function carryOf(input: unknown, lim: {
21
+ turns: number;
22
+ turnChars: number;
23
+ replyChars: number;
24
+ summaryChars: number;
25
+ bytes: number;
26
+ }): ConversationCarry;
27
+ /**
28
+ * The flow body of a conversation. Register it with {@link conversation$} (which also builds the
29
+ * definition) or call it from your own runner.
30
+ */
31
+ export declare function conversationRunner(config: ConversationConfig, shared?: {
32
+ turnEffectId: string;
33
+ }): FlowRunner<ConversationCarry | Record<string, never>, ConversationResult>;
34
+ export interface ConversationFlowOptions {
35
+ /** The flow id (default `"conversation"`). */
36
+ id?: string;
37
+ name?: string;
38
+ version?: string;
39
+ }
40
+ /** A conversation flow plus what a client needs to drive it. */
41
+ export type ConversationFlow = RegisteredFlow<ConversationCarry | Record<string, never>, ConversationResult> & {
42
+ /** `"owner"` (default) or `"shared"` (a participant set; see {@link SharedConfig}). */
43
+ readonly mode: "owner" | "shared";
44
+ readonly config: ConversationConfig;
45
+ /** Shared mode only: the turn flow and the effect id to register. */
46
+ readonly sharedTurn?: {
47
+ flow: RegisteredFlow<TurnInput, Omit<TurnResult, "turnExecutionId">>;
48
+ effectId: string;
49
+ signals: Map<string, AbortSignal>;
50
+ };
51
+ };
52
+ /**
53
+ * Build the registered flow of a conversation. Register it on the runtime
54
+ * (`runtime.registerFlow(flow.definition, flow.runner)`) and drive it with {@link createConversations}.
55
+ * Needs `kernel.features.inbox` and `kernel.features.continueAsNew` on the runtime.
56
+ */
57
+ export declare function conversation$(config: ConversationConfig, options?: ConversationFlowOptions): ConversationFlow;
58
+ export { registerSharedTurnEffect, sharedTurnEffect };
59
+ //# sourceMappingURL=conversation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"conversation.d.ts","sourceRoot":"","sources":["../src/conversation.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAoB,UAAU,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAmB/F,OAAO,EACL,KAAK,SAAS,EACd,KAAK,UAAU,EACf,wBAAwB,EACxB,gBAAgB,EAEjB,MAAM,QAAQ,CAAC;AAChB,OAAO,EAGL,KAAK,iBAAiB,EACtB,KAAK,kBAAkB,EACvB,KAAK,kBAAkB,EAKvB,KAAK,YAA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