@tangle-network/agent-app 0.60.68 → 0.60.70

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.
@@ -4,6 +4,7 @@ import {
4
4
  DEFAULT_PREWARM_CLAIM_TABLE,
5
5
  DEFAULT_PROVISION_TIMEOUT_MS,
6
6
  DEFAULT_SANDBOX_RESOURCES,
7
+ DEFAULT_WARM_LEASE_TABLE,
7
8
  ENV_TOTAL_MAX_BYTES,
8
9
  ENV_VALUE_MAX_BYTES,
9
10
  PREWARM_CLAIM_TABLE_DDL,
@@ -16,7 +17,10 @@ import {
16
17
  SandboxProvisioningFailedElsewhereError,
17
18
  SandboxRecoveryFailedError,
18
19
  SandboxRuntimeAuthRefreshError,
20
+ WARM_LEASE_TABLE_DDL,
21
+ WARM_SLOTS,
19
22
  adaptSandboxStream,
23
+ addColdArrival,
20
24
  applyPromptTokenLimits,
21
25
  assertEnvWithinLimits,
22
26
  assertProvisionPayloadWithinCap,
@@ -31,10 +35,13 @@ import {
31
35
  classifySeveredStream,
32
36
  collectSandboxPromptText,
33
37
  createD1PrewarmClaimStore,
38
+ createD1WarmLeaseStore,
34
39
  createSandboxPrewarmer,
35
40
  createSandboxTerminalConnectionRoute,
41
+ createWarmLeases,
36
42
  createWorkspacePrewarmRoute,
37
43
  createWorkspaceSandboxManager,
44
+ decaySlots,
38
45
  deferredCorpusHash,
39
46
  deleteSecret,
40
47
  detectInteractiveQuestion,
@@ -49,6 +56,7 @@ import {
49
56
  mergeHistoryIntoParts,
50
57
  mintSandboxScopedToken,
51
58
  peekWorkspaceSandbox,
59
+ predictColdArrival,
52
60
  readSandboxBinaryBytes,
53
61
  requireTransportableModel,
54
62
  resetClientCache,
@@ -72,8 +80,11 @@ import {
72
80
  syncSandboxMemberAdd,
73
81
  syncSandboxMemberRemove,
74
82
  syncSandboxMemberRole,
83
+ utcDay,
84
+ warmBinOf,
85
+ warmWeekdayOf,
75
86
  writeProfileFilesToBox
76
- } from "../chunk-7DG6GGRN.js";
87
+ } from "../chunk-GIJZAJ5W.js";
77
88
  import {
78
89
  EGRESS_PROXY_RECOVERY_PHASE,
79
90
  EGRESS_PROXY_RECOVERY_REQUIRED,
@@ -128,6 +139,7 @@ export {
128
139
  DEFAULT_PREWARM_CLAIM_TABLE,
129
140
  DEFAULT_PROVISION_TIMEOUT_MS,
130
141
  DEFAULT_SANDBOX_RESOURCES,
142
+ DEFAULT_WARM_LEASE_TABLE,
131
143
  EGRESS_PROXY_RECOVERY_PHASE,
132
144
  EGRESS_PROXY_RECOVERY_REQUIRED,
133
145
  ENV_TOTAL_MAX_BYTES,
@@ -145,6 +157,8 @@ export {
145
157
  SandboxRecoveryFailedError,
146
158
  SandboxRuntimeAuthRefreshError,
147
159
  SandboxTransientDeadlineError,
160
+ WARM_LEASE_TABLE_DDL,
161
+ WARM_SLOTS,
148
162
  WORKSPACE_SANDBOX_HOST_EXHAUSTED,
149
163
  WORKSPACE_SANDBOX_MISSING,
150
164
  WORKSPACE_SANDBOX_RECOVERY_ACTIONS,
@@ -153,6 +167,7 @@ export {
153
167
  WORKSPACE_SANDBOX_UNRECOVERABLE,
154
168
  WorkspaceSandboxRecoveryRequiredError,
155
169
  adaptSandboxStream,
170
+ addColdArrival,
156
171
  applyPromptTokenLimits,
157
172
  assertEnvWithinLimits,
158
173
  assertProvisionPayloadWithinCap,
@@ -169,11 +184,14 @@ export {
169
184
  classifySeveredStream,
170
185
  collectSandboxPromptText,
171
186
  createD1PrewarmClaimStore,
187
+ createD1WarmLeaseStore,
172
188
  createSandboxPrewarmer,
173
189
  createSandboxTerminalConnectionRoute,
190
+ createWarmLeases,
174
191
  createWorkspacePrewarmRoute,
175
192
  createWorkspaceSandboxManager,
176
193
  createWorkspaceSandboxRecoveryManager,
194
+ decaySlots,
177
195
  deferredCorpusHash,
178
196
  deleteSecret,
179
197
  detectInteractiveQuestion,
@@ -200,6 +218,7 @@ export {
200
218
  mergeHistoryIntoParts,
201
219
  mintSandboxScopedToken,
202
220
  peekWorkspaceSandbox,
221
+ predictColdArrival,
203
222
  preferredWorkspaceSandboxRecoveryBoxKey,
204
223
  readSandboxBinaryBytes,
205
224
  requireTransportableModel,
@@ -228,6 +247,9 @@ export {
228
247
  syncSandboxMemberAdd,
229
248
  syncSandboxMemberRemove,
230
249
  syncSandboxMemberRole,
250
+ utcDay,
251
+ warmBinOf,
252
+ warmWeekdayOf,
231
253
  workspaceSandboxRecoveryDiagnostic,
232
254
  workspaceSandboxRecoveryFromError,
233
255
  workspaceSandboxRecoveryMessage,
@@ -0,0 +1,33 @@
1
+ import { type WarmLeaseStore } from './warm-lease';
2
+ /**
3
+ * `createD1WarmLeaseStore`: the `WarmLeaseStore` every Workers product uses,
4
+ * one row per key in one table.
5
+ *
6
+ * Race-sensitive steps are single statements. `begin` is an upsert whose SET
7
+ * expressions read the old row, so two isolates that signal at once agree on
8
+ * one lease id and only its owner runs the warm. `markUsed` claims the first
9
+ * use with a conditional UPDATE … RETURNING, so two turns cannot both count as
10
+ * the hit. The prediction slots are a decayed statistic and are written
11
+ * without a fence: a lost increment under a race costs nothing.
12
+ *
13
+ * The table is the product's migration (`WARM_LEASE_TABLE_DDL`); the store
14
+ * never runs DDL, for the same reason as `createD1PrewarmClaimStore`.
15
+ */
16
+ export declare const DEFAULT_WARM_LEASE_TABLE = "sandbox_warm_lease";
17
+ /** Paste into a migration. Times are epoch milliseconds; 0 means never. */
18
+ export declare const WARM_LEASE_TABLE_DDL = "CREATE TABLE IF NOT EXISTS sandbox_warm_lease (\n key TEXT PRIMARY KEY,\n lease_id TEXT,\n reason TEXT,\n started_at INTEGER NOT NULL DEFAULT 0,\n hold_until INTEGER NOT NULL DEFAULT 0,\n warm_at INTEGER NOT NULL DEFAULT 0,\n used_at INTEGER NOT NULL DEFAULT 0,\n resumed INTEGER NOT NULL DEFAULT 0,\n ping_at INTEGER NOT NULL DEFAULT 0,\n last_turn_at INTEGER NOT NULL DEFAULT 0,\n day TEXT NOT NULL DEFAULT '',\n day_warm_ms INTEGER NOT NULL DEFAULT 0,\n threshold REAL NOT NULL DEFAULT 0,\n slots TEXT NOT NULL DEFAULT '',\n slots_at INTEGER NOT NULL DEFAULT 0,\n first_seen_at INTEGER NOT NULL DEFAULT 0,\n predicted_at INTEGER NOT NULL DEFAULT 0\n)";
19
+ /** The D1 surface this store uses: `prepare().bind()` with `first`, `run` and `all`. A real `D1Database` satisfies it. */
20
+ export interface WarmLeaseD1Like {
21
+ prepare(query: string): {
22
+ bind(...values: unknown[]): {
23
+ first<T = Record<string, unknown>>(): Promise<T | null>;
24
+ run(): Promise<unknown>;
25
+ all<T = Record<string, unknown>>(): Promise<{
26
+ results: T[];
27
+ }>;
28
+ };
29
+ };
30
+ }
31
+ export declare function createD1WarmLeaseStore(db: WarmLeaseD1Like, options?: {
32
+ table?: string;
33
+ }): WarmLeaseStore;
@@ -0,0 +1,210 @@
1
+ /**
2
+ * `createWarmLeases`: warm a workspace's box shortly before a member needs it,
3
+ * hold it while the conversation continues, and let the platform suspend it
4
+ * afterwards. One primitive for every warm signal, so a page open, a composer
5
+ * focus, an inbound line message and a learned weekly pattern share one
6
+ * dedupe, one budget and one event stream.
7
+ *
8
+ * WHY A LEASE. Drew cancelled always-on keep-warm (2026-10-11): a warm box must
9
+ * be earned by a signal and must cost a bounded amount when the signal was
10
+ * wrong. Measured on Hospitality (2026-10-04..10-11, timestamps only): every
11
+ * human first message after 30 min of quiet landed on a suspended box, and the
12
+ * cold first reply took 68 s on the web and 76 s on a line.
13
+ *
14
+ * WHO SUSPENDS. Not this module. `POST /v1/sandboxes/:id/stop` suspends a box
15
+ * even while a turn runs in it (agent-dev-container
16
+ * `routes/projects/lifecycle.ts`), whereas the platform's idle reaper re-checks
17
+ * the sidecar for live work before it suspends. So a lease only ever resumes
18
+ * and, during a burst hold, pings. An unused warm ends when the box's own idle
19
+ * timeout passes; create boxes with `idleTimeoutSeconds` near the warm hold
20
+ * (600 s) to make a wrong warm cost about ten minutes, and tell this module that
21
+ * value through `boxIdleMs` so its accounting matches the platform.
22
+ *
23
+ * WHAT IT COSTS. Each lease that ends without a turn charges the box time it
24
+ * caused (until the box's idle timeout after its last warm activity) to that
25
+ * key's UTC day. Signals listed in `budgetedReasons` are refused once the day's
26
+ * charge reaches `dailyBudgetMs`. A box that was already running when a signal
27
+ * arrived is charged nothing: the warm did not cause that time.
28
+ *
29
+ * PREDICTION. Every turn that arrives after `boxIdleMs` of quiet (a cold
30
+ * arrival) adds to a decayed count for its ten-minute bin of the day and its
31
+ * weekday. Hour-of-week bins were too coarse: one arrival a day in an hour is
32
+ * a 15% chance for any ten-minute warm, so a shift-start ramp never crossed a
33
+ * useful threshold. `sweep()` warms a key when the predicted chance of a cold
34
+ * arrival in the next `holdMs` reaches that key's threshold, at most once per
35
+ * hour, within the budget. The threshold tunes itself: a predicted warm that is used lowers it,
36
+ * one that is wasted raises it.
37
+ *
38
+ * EVENTS. `warm_started`, `warm_hit`, `warm_wasted`, `warm_declined` and
39
+ * `warm_failed` each carry the key and the reason, so a product can compute hit
40
+ * rate and wasted minutes per workspace from its logs alone.
41
+ */
42
+ /** Why a warm was requested. Products may add their own reasons. */
43
+ export type WarmReason = 'page-open' | 'composer-focus' | 'line-ingress' | 'member-activity' | 'predicted' | 'scheduled' | (string & {});
44
+ /** What the product's `warm` did to the box. */
45
+ export type WarmBoxOutcome =
46
+ /** The box was stopped and is now running: this warm caused its up-time. */
47
+ 'resumed'
48
+ /** The box was already running: nothing to warm, nothing charged. */
49
+ | 'running'
50
+ /** No box exists for this key. Leases never create boxes. */
51
+ | 'absent';
52
+ export type WarmLeaseEvent = {
53
+ type: 'warm_started';
54
+ key: string;
55
+ reason: WarmReason;
56
+ outcome: WarmBoxOutcome;
57
+ ms: number;
58
+ } | {
59
+ type: 'warm_hit';
60
+ key: string;
61
+ reason: WarmReason;
62
+ leadMs: number;
63
+ } | {
64
+ type: 'warm_wasted';
65
+ key: string;
66
+ reason: WarmReason;
67
+ minutes: number;
68
+ } | {
69
+ type: 'warm_declined';
70
+ key: string;
71
+ reason: WarmReason;
72
+ why: 'budget' | 'absent';
73
+ } | {
74
+ type: 'warm_failed';
75
+ key: string;
76
+ reason: WarmReason;
77
+ error: string;
78
+ };
79
+ export type WarmSignalOutcome =
80
+ /** This call started a lease and ran the product's warm. */
81
+ 'started'
82
+ /** A lease was already live (here or in another isolate); its hold was extended. */
83
+ | 'extended' | 'declined' | 'failed';
84
+ export interface WarmSignalResult {
85
+ outcome: WarmSignalOutcome;
86
+ box?: WarmBoxOutcome;
87
+ }
88
+ export interface WarmTurnResult {
89
+ /** The turn landed on a box a lease had already warmed. */
90
+ hit: boolean;
91
+ /** The turn arrived after `boxIdleMs` of quiet on this key. */
92
+ coldArrival: boolean;
93
+ }
94
+ export interface WarmSweepReport {
95
+ ended: number;
96
+ wasted: number;
97
+ pinged: number;
98
+ predicted: number;
99
+ /** Keys whose ping or predicted warm threw; the rest of the batch still ran. */
100
+ errors: number;
101
+ }
102
+ /** One key's row. Times are epoch milliseconds; 0 means never. */
103
+ export interface WarmLeaseRow {
104
+ key: string;
105
+ leaseId: string | null;
106
+ reason: string | null;
107
+ startedAt: number;
108
+ holdUntil: number;
109
+ warmAt: number;
110
+ usedAt: number;
111
+ resumed: boolean;
112
+ pingAt: number;
113
+ lastTurnAt: number;
114
+ day: string;
115
+ dayWarmMs: number;
116
+ threshold: number;
117
+ slots: number[];
118
+ slotsAt: number;
119
+ firstSeenAt: number;
120
+ predictedAt: number;
121
+ }
122
+ /** Persistence for leases. `begin` and `markUsed` must be atomic across isolates. */
123
+ export interface WarmLeaseStore {
124
+ read(key: string): Promise<WarmLeaseRow | null>;
125
+ /**
126
+ * Start a lease with `leaseId` when none is live, otherwise extend the live
127
+ * one's hold to at least `holdUntil`. Returns the live lease id after the
128
+ * write; the caller started the lease exactly when it equals `leaseId`.
129
+ */
130
+ begin(key: string, leaseId: string, reason: string, now: number, holdUntil: number): Promise<string>;
131
+ /** Record the result of this lease's warm. No-op for a superseded lease. */
132
+ markWarm(key: string, leaseId: string, warmAt: number, resumed: boolean): Promise<void>;
133
+ /**
134
+ * Record a turn: mark the live lease used (first turn only), extend its hold
135
+ * to `holdUntil`, and store `lastTurnAt`. Returns the row as it was BEFORE
136
+ * the write, so the caller can tell a hit and a cold arrival apart.
137
+ */
138
+ markUsed(key: string, now: number, holdUntil: number): Promise<WarmLeaseRow | null>;
139
+ /**
140
+ * End `leaseId`, charging `chargeMs` to `day` and setting the predicted-warm
141
+ * threshold when one is given. No-op for a superseded lease.
142
+ */
143
+ end(key: string, leaseId: string, day: string, chargeMs: number, threshold?: number): Promise<void>;
144
+ /** Overwrite the prediction fields. Lossy under races by design: it is a statistic. */
145
+ writeProfile(key: string, slots: number[], slotsAt: number, firstSeenAt: number): Promise<void>;
146
+ markPinged(key: string, at: number): Promise<void>;
147
+ markPredicted(key: string, at: number): Promise<void>;
148
+ /** Bounded batches for `sweep`. */
149
+ listExpired(now: number, limit: number): Promise<WarmLeaseRow[]>;
150
+ listHeld(now: number, limit: number): Promise<WarmLeaseRow[]>;
151
+ listPredictable(now: number, limit: number): Promise<WarmLeaseRow[]>;
152
+ }
153
+ export interface WarmLeasesOptions {
154
+ store: WarmLeaseStore;
155
+ /** Resume the key's box if it is stopped. Never create one. */
156
+ warm(key: string, reason: WarmReason): Promise<WarmBoxOutcome>;
157
+ /**
158
+ * Optional: touch the running box through a path the platform counts as
159
+ * activity (an exec of `true`). Needed only when `burstHoldMs` exceeds
160
+ * `boxIdleMs`; without it a burst hold is just the box's own idle timeout.
161
+ */
162
+ keepAlive?(key: string): Promise<void>;
163
+ /** The idle timeout the key's boxes were created with. Default 30 min, the platform default. */
164
+ boxIdleMs?: number;
165
+ /** How long a warm waits for its first turn. Default 10 min. */
166
+ holdMs?: number;
167
+ /** How long the box stays held after a turn. Default `boxIdleMs` (no pings). */
168
+ burstHoldMs?: number;
169
+ /** Unused-warm box time allowed per key per UTC day. Default 30 min. */
170
+ dailyBudgetMs?: number;
171
+ /** Reasons subject to the budget. Default page-open, member-activity, predicted, scheduled. */
172
+ budgetedReasons?: readonly string[];
173
+ /** Starting predicted-warm threshold, a probability. Default 0.25. */
174
+ initialThreshold?: number;
175
+ onEvent?(event: WarmLeaseEvent): void;
176
+ now?(): number;
177
+ newId?(): string;
178
+ }
179
+ export interface WarmLeases {
180
+ /** A signal that a member may need `key`'s box soon. Awaits the warm when it starts one. */
181
+ signal(key: string, reason: WarmReason): Promise<WarmSignalResult>;
182
+ /** Call when a turn is admitted for `key`, before its box is placed. */
183
+ turn(key: string): Promise<WarmTurnResult>;
184
+ /** End expired leases, ping held boxes, and start predicted warms. Run from a cron. */
185
+ sweep(options?: {
186
+ limit?: number;
187
+ }): Promise<WarmSweepReport>;
188
+ }
189
+ /** 144 ten-minute bins of the UTC day, then 7 weekday counts (Monday first). */
190
+ export declare const WARM_SLOTS = 151;
191
+ /** UTC ten-minute bin of the day, 0..143. */
192
+ export declare function warmBinOf(at: number): number;
193
+ /** UTC weekday, Monday = 0. */
194
+ export declare function warmWeekdayOf(at: number): number;
195
+ export declare function utcDay(at: number): string;
196
+ /** Decay every slot to `at` with a 14-day half-life. */
197
+ export declare function decaySlots(slots: readonly number[], from: number, at: number): number[];
198
+ /** Record one cold arrival at `at`. */
199
+ export declare function addColdArrival(slots: readonly number[], slotsAt: number, at: number): number[];
200
+ /**
201
+ * Chance of at least one cold arrival in `[at, at + windowMs)`.
202
+ *
203
+ * Each ten-minute bin's rate is its decayed count over the effective days
204
+ * observed, smoothed over its neighbours (a shift that starts at 07:00 sends
205
+ * its first message anywhere from 06:55 to 07:15), and scaled by how busy the
206
+ * window's weekday is against the average weekday. The weekday factor is
207
+ * smoothed toward 1 because two weeks hold only two of each weekday.
208
+ */
209
+ export declare function predictColdArrival(row: Pick<WarmLeaseRow, 'slots' | 'slotsAt' | 'firstSeenAt'>, at: number, windowMs: number): number;
210
+ export declare function createWarmLeases(options: WarmLeasesOptions): WarmLeases;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-app",
3
- "version": "0.60.68",
3
+ "version": "0.60.70",
4
4
  "packageManager": "pnpm@11.24.0",
5
5
  "description": "Build agent applications with typed chat, tools, sandboxes, integrations, billing, and evaluation.",
6
6
  "keywords": [