@zhivex-ai/core 1.30.0 → 1.30.2

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 (63) hide show
  1. package/dist/agent/common.d.ts.map +1 -1
  2. package/dist/agent/common.js +4 -0
  3. package/dist/agent/common.js.map +1 -1
  4. package/dist/agent/context.d.ts.map +1 -1
  5. package/dist/agent/context.js +5 -2
  6. package/dist/agent/context.js.map +1 -1
  7. package/dist/agent/tool-execution.d.ts.map +1 -1
  8. package/dist/agent/tool-execution.js +14 -2
  9. package/dist/agent/tool-execution.js.map +1 -1
  10. package/dist/agent-store/file.d.ts.map +1 -1
  11. package/dist/agent-store/file.js +196 -93
  12. package/dist/agent-store/file.js.map +1 -1
  13. package/dist/agent-store/memory.d.ts.map +1 -1
  14. package/dist/agent-store/memory.js +18 -17
  15. package/dist/agent-store/memory.js.map +1 -1
  16. package/dist/agent-store/postgres.d.ts.map +1 -1
  17. package/dist/agent-store/postgres.js +181 -47
  18. package/dist/agent-store/postgres.js.map +1 -1
  19. package/dist/agent-store/shared.d.ts +20 -0
  20. package/dist/agent-store/shared.d.ts.map +1 -1
  21. package/dist/agent-store/shared.js +50 -10
  22. package/dist/agent-store/shared.js.map +1 -1
  23. package/dist/agent-store/sqlite.d.ts.map +1 -1
  24. package/dist/agent-store/sqlite.js +103 -54
  25. package/dist/agent-store/sqlite.js.map +1 -1
  26. package/dist/api-stability.d.ts.map +1 -1
  27. package/dist/api-stability.js +1 -0
  28. package/dist/api-stability.js.map +1 -1
  29. package/dist/computer-use.d.ts +32 -6
  30. package/dist/computer-use.d.ts.map +1 -1
  31. package/dist/computer-use.js +79 -12
  32. package/dist/computer-use.js.map +1 -1
  33. package/dist/experimental-entry.d.ts +2 -2
  34. package/dist/experimental-entry.d.ts.map +1 -1
  35. package/dist/experimental-entry.js +1 -1
  36. package/dist/experimental-entry.js.map +1 -1
  37. package/dist/generate-object.d.ts.map +1 -1
  38. package/dist/generate-object.js +3 -11
  39. package/dist/generate-object.js.map +1 -1
  40. package/dist/generate-text.d.ts.map +1 -1
  41. package/dist/generate-text.js +72 -16
  42. package/dist/generate-text.js.map +1 -1
  43. package/dist/index.d.ts +2 -2
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +1 -1
  46. package/dist/index.js.map +1 -1
  47. package/dist/middleware-runtime.d.ts.map +1 -1
  48. package/dist/middleware-runtime.js +16 -6
  49. package/dist/middleware-runtime.js.map +1 -1
  50. package/dist/stream.d.ts +6 -0
  51. package/dist/stream.d.ts.map +1 -1
  52. package/dist/stream.js +59 -28
  53. package/dist/stream.js.map +1 -1
  54. package/dist/tool-execution-outcome.d.ts +14 -0
  55. package/dist/tool-execution-outcome.d.ts.map +1 -0
  56. package/dist/tool-execution-outcome.js +6 -0
  57. package/dist/tool-execution-outcome.js.map +1 -0
  58. package/dist/types/generation.d.ts +4 -0
  59. package/dist/types/generation.d.ts.map +1 -1
  60. package/dist/workflow.d.ts.map +1 -1
  61. package/dist/workflow.js +39 -5
  62. package/dist/workflow.js.map +1 -1
  63. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
1
  import { normalizeAgentRunState } from "../agent-state.js";
2
2
  import { ConflictError, ValidationError } from "../errors.js";
3
- import { scopedKey, resolveScope, cloneState, assertLeaseOwner, assertExpectedRevision, nextStoredState, scopePrefix, listStates, validateLeaseOptions, cloneJournalEntry, assertJournalRevision, nextJournalEntry, defaultMemoryKey, defaultMemoryMessages } from "./shared.js";
3
+ import { scopedKey, matchesScope, journalKey as canonicalJournalKey, resolveScope, cloneState, assertLeaseOwner, assertExpectedRevision, nextStoredState, listStates, validateLeaseOptions, cloneJournalEntry, assertJournalRevision, nextJournalEntry, defaultMemoryKey, defaultMemoryMessages } from "./shared.js";
4
4
  const cloneMessages = (messages) => JSON.parse(JSON.stringify(messages));
5
5
  export const createInMemoryAgentRunStore = (options = {}) => {
6
6
  const states = new Map();
@@ -10,7 +10,7 @@ export const createInMemoryAgentRunStore = (options = {}) => {
10
10
  const journal = new Map();
11
11
  const runKey = (runId, scope) => scopedKey(resolveScope(options.scope, scope), runId);
12
12
  const idempotencyKey = (key, scope) => scopedKey(resolveScope(options.scope, scope), key);
13
- const journalKey = (runId, toolCallId, scope) => `${runKey(runId, scope)}:${toolCallId}`;
13
+ const journalKey = (runId, toolCallId, scope) => canonicalJournalKey(resolveScope(options.scope, scope), runId, toolCallId);
14
14
  const removeParentIndex = (state) => {
15
15
  if (!state?.parentRunId) {
16
16
  return;
@@ -68,15 +68,17 @@ export const createInMemoryAgentRunStore = (options = {}) => {
68
68
  const current = states.get(runKey(state.runId, scope));
69
69
  assertExpectedRevision(current, saveOptions?.expectedRevision);
70
70
  const normalized = nextStoredState(state, saveOptions);
71
- removeParentIndex(current);
72
- states.set(runKey(normalized.runId, scope), cloneState({ ...normalized, ...(scope ? { scope } : {}) }));
73
71
  if (normalized.idempotencyKey) {
74
72
  const owner = idempotencyKeys.get(idempotencyKey(normalized.idempotencyKey, scope));
75
73
  if (owner && owner !== runKey(normalized.runId, scope)) {
76
74
  throw new ConflictError("AgentRunState idempotency key conflict.");
77
75
  }
78
- idempotencyKeys.set(idempotencyKey(normalized.idempotencyKey, scope), runKey(normalized.runId, scope));
79
76
  }
77
+ const stored = cloneState({ ...normalized, ...(scope ? { scope } : {}) });
78
+ removeParentIndex(current);
79
+ states.set(runKey(normalized.runId, scope), stored);
80
+ if (normalized.idempotencyKey)
81
+ idempotencyKeys.set(idempotencyKey(normalized.idempotencyKey, scope), runKey(normalized.runId, scope));
80
82
  if (normalized.parentRunId) {
81
83
  const parentKey = scopedKey(scope, normalized.parentRunId);
82
84
  const children = parentRunIds.get(parentKey) ?? new Set();
@@ -93,18 +95,18 @@ export const createInMemoryAgentRunStore = (options = {}) => {
93
95
  removeParentIndex(state);
94
96
  states.delete(key);
95
97
  leases.delete(key);
96
- for (const journalEntryKey of journal.keys()) {
97
- if (journalEntryKey.startsWith(`${key}:`))
98
+ for (const [journalEntryKey, entry] of journal) {
99
+ if (entry.runId === runId && matchesScope(entry.scope, resolveScope(options.scope, scope)))
98
100
  journal.delete(journalEntryKey);
99
101
  }
100
102
  },
101
103
  list(listOptions, scope) {
102
- const prefix = scopePrefix(resolveScope(options.scope, scope));
103
- return listStates([...states.entries()].filter(([key]) => key.startsWith(prefix)).map(([, state]) => state), listOptions);
104
+ const targetScope = resolveScope(options.scope, scope);
105
+ return listStates([...states.values()].filter(state => !targetScope || matchesScope(state.scope, targetScope)), listOptions);
104
106
  },
105
107
  deleteExpired(retention, scope) {
106
- const prefix = scopePrefix(resolveScope(options.scope, scope));
107
- const candidates = listStates([...states.entries()].filter(([key]) => key.startsWith(prefix)).map(([, state]) => state), {
108
+ const targetScope = resolveScope(options.scope, scope);
109
+ const candidates = listStates([...states.values()].filter(state => !targetScope || matchesScope(state.scope, targetScope)), {
108
110
  statuses: retention.statuses,
109
111
  updatedBefore: retention.before,
110
112
  limit: retention.limit ?? 1_000
@@ -151,10 +153,9 @@ export const createInMemoryAgentRunStore = (options = {}) => {
151
153
  return this.loadToolCall?.(runId, toolCallId, scope);
152
154
  },
153
155
  listToolCalls(runId, scope) {
154
- const prefix = `${runKey(runId, scope)}:`;
155
- return [...journal.entries()]
156
- .filter(([key]) => key.startsWith(prefix))
157
- .map(([, entry]) => cloneJournalEntry(entry))
156
+ return [...journal.values()]
157
+ .filter(entry => entry.runId === runId && matchesScope(entry.scope, resolveScope(options.scope, scope)))
158
+ .map(entry => cloneJournalEntry(entry))
158
159
  .sort((left, right) => left.updatedAt - right.updatedAt || left.toolCallId.localeCompare(right.toolCallId));
159
160
  },
160
161
  saveToolCall(entry, journalOptions) {
@@ -165,7 +166,7 @@ export const createInMemoryAgentRunStore = (options = {}) => {
165
166
  const key = journalKey(entry.runId, entry.toolCallId, scope);
166
167
  const current = journal.get(key);
167
168
  assertJournalRevision(current, journalOptions?.expectedRevision);
168
- const next = nextJournalEntry(entry, journalOptions);
169
+ const next = nextJournalEntry({ ...entry, ...(scope ? { scope } : {}) }, journalOptions);
169
170
  journal.set(key, next);
170
171
  return cloneJournalEntry(next);
171
172
  },
@@ -188,7 +189,7 @@ export const createInMemoryAgentMemoryStore = (options = {}) => {
188
189
  const memories = new Map(Object.entries(options.initialMessages ?? {}).map(([key, messages]) => [key, cloneMessages(messages)]));
189
190
  return {
190
191
  load(context) {
191
- return cloneMessages(memories.get(keyFor(context)) ?? (context.agentId ? options.initialMessages?.[context.agentId] : undefined) ?? []);
192
+ return cloneMessages(memories.get(keyFor(context)) ?? (!context.scope ? options.initialMessages?.[context.runId] : undefined) ?? (context.agentId ? options.initialMessages?.[context.agentId] : undefined) ?? []);
192
193
  },
193
194
  save(context) {
194
195
  memories.set(keyFor(context), cloneMessages(selectMessages(context.state)));
@@ -1 +1 @@
1
- {"version":3,"file":"memory.js","sourceRoot":"","sources":["../../src/agent-store/memory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AAC3D,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAY9D,OAAO,EACL,SAAS,EACT,YAAY,EACZ,UAAU,EACV,gBAAgB,EAChB,sBAAsB,EACtB,eAAe,EACf,WAAW,EACX,UAAU,EACV,oBAAoB,EACpB,iBAAiB,EACjB,qBAAqB,EACrB,gBAAgB,EAChB,gBAAgB,EAChB,qBAAqB,EACtB,MAAM,aAAa,CAAC;AAErB,MAAM,aAAa,GAAG,CAAC,QAAwB,EAAkB,EAAE,CACjE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAmB,CAAC;AAEzD,MAAM,CAAC,MAAM,2BAA2B,GAAG,CAAC,OAAO,GAA8B,EAAE,EAAiB,EAAE;IACpG,MAAM,MAAM,GAAG,IAAI,GAAG,EAAyB,CAAC;IAChD,MAAM,eAAe,GAAG,IAAI,GAAG,EAAkB,CAAC;IAClD,MAAM,YAAY,GAAG,IAAI,GAAG,EAAu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AAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,eAAe,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,eAAe,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,IAAI,EAAE,CAAC,CAAC;QACrN,CAAC;QACD,IAAI,CAAC,OAAO;YACV,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,aAAa,CAAC,cAAc,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QAC9E,CAAC;KACF,CAAC;AACJ,CAAC,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"postgres.d.ts","sourceRoot":"","sources":["../../src/agent-store/postgres.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAEV,gBAAgB,EAGhB,aAAa,EAIb,+BAA+B,EAC/B,4BAA4B,EAE7B,MAAM,aAAa,CAAC;AA+DrB,eAAO,MAAM,2BAA2B,YAAa,4BAA4B,KAAG,aAuWnF,CAAC;AAEF,eAAO,MAAM,8BAA8B,YAAa,+BAA+B,KAAG,gBAoCzF,CAAC"}
1
+ {"version":3,"file":"postgres.d.ts","sourceRoot":"","sources":["../../src/agent-store/postgres.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAEV,gBAAgB,EAGhB,aAAa,EAIb,+BAA+B,EAC/B,4BAA4B,EAE7B,MAAM,aAAa,CAAC;AAsErB,eAAO,MAAM,2BAA2B,YAAa,4BAA4B,KAAG,aAscnF,CAAC;AAEF,eAAO,MAAM,8BAA8B,YAAa,+BAA+B,KAAG,gBAmDzF,CAAC"}
@@ -1,7 +1,7 @@
1
1
  import { normalizeAgentRunState } from "../agent-state.js";
2
2
  import { ConflictError, ValidationError } from "../errors.js";
3
3
  import { assertPostgresClient } from "../postgres-client.js";
4
- import { validateIdentifier, scopedKey, resolveScope, getRecordField, nextStoredState, scopePrefix, listStates, validateLeaseOptions, cloneJournalEntry, nextJournalEntry, defaultMemoryKey, defaultMemoryMessages } from "./shared.js";
4
+ import { validateIdentifier, scopedKey, legacyScopedKey, matchesRun, matchesScope, resolveScope, getRecordField, nextStoredState, listStates, parseAgentRunListOptions, validateLeaseOptions, cloneJournalEntry, nextJournalEntry, defaultMemoryKey, legacyDefaultMemoryKey, encodeAgentMemory, decodeAgentMemory, LEGACY_MEMORY_MIGRATION_MESSAGE, defaultMemoryMessages } from "./shared.js";
5
5
  const isConcurrentPostgresTableCreationConflict = (error) => {
6
6
  if (!error || typeof error !== "object")
7
7
  return false;
@@ -90,8 +90,39 @@ export const createPostgresAgentRunStore = (options) => {
90
90
  updated_at_ms BIGINT NOT NULL,
91
91
  PRIMARY KEY (run_key, tool_call_id)
92
92
  )`;
93
+ // Use persisted logical timestamps, not the database write timestamp. These
94
+ // expressions also apply to legacy rows without changing their physical keys.
95
+ const sortTimeSql = "COALESCE((state_json->>'updatedAt')::double precision, (state_json->>'startedAt')::double precision, 0)";
96
+ const updatedTimeSql = "COALESCE((state_json->>'updatedAt')::double precision, 0)";
97
+ const tenantSql = "(state_json #>> '{scope,tenantId}')";
98
+ const userSql = "(state_json #>> '{scope,userId}')";
99
+ const namespaceSql = "(state_json #>> '{scope,namespace}')";
100
+ // Scope strings are unbounded. Hash index entries so valid long identifiers
101
+ // cannot exceed PostgreSQL's B-tree tuple limit; raw predicates below still
102
+ // establish exact identity even if two values ever share a digest.
103
+ const scopeHashSql = (expression) => `md5(${expression})`;
104
+ // JS string ordering compares UTF-16 code units. PostgreSQL's C collation
105
+ // compares UTF-8 bytes instead, so supplementary characters need surrogate
106
+ // pairs in this sort key to preserve existing cursors exactly.
107
+ const runIdSortSql = `(SELECT string_agg(
108
+ CASE WHEN ascii(character) <= 65535 THEN lpad(to_hex(ascii(character)), 4, '0')
109
+ ELSE lpad(to_hex(55296 + (ascii(character) - 65536) / 1024), 4, '0')
110
+ || lpad(to_hex(56320 + (ascii(character) - 65536) % 1024), 4, '0') END,
111
+ '' ORDER BY position)
112
+ FROM regexp_split_to_table(state_json->>'runId', '') WITH ORDINALITY AS units(character, position)) COLLATE "C"`;
113
+ // Recreate scopedKey from logical JSON identity, including legacy rows. Build
114
+ // compact JSON explicitly: json[b]_build_array textual output adds spaces.
115
+ const scopeTupleSql = `CASE WHEN state_json->'scope' IS NULL THEN 'null' ELSE
116
+ '[' || COALESCE((state_json #> '{scope,namespace}')::text, 'null') || ','
117
+ || (state_json #> '{scope,tenantId}')::text || ','
118
+ || COALESCE((state_json #> '{scope,userId}')::text, 'null') || ']' END`;
119
+ const scopedSortSql = `('agent-run:v2:' || encode(sha256(convert_to(
120
+ '[' || to_json((${scopeTupleSql})::text)::text || ',' || (state_json->'runId')::text || ']',
121
+ 'UTF8')), 'hex')) COLLATE "C"`;
93
122
  const createIndexesSql = `
94
123
  CREATE INDEX IF NOT EXISTS ${tableName}_updated_idx ON ${tableName} (updated_at_ms DESC, run_id);
124
+ CREATE INDEX IF NOT EXISTS ${tableName}_scope_hash_page_idx ON ${tableName} ((${scopeHashSql(tenantSql)}), (${scopeHashSql(userSql)}), (${scopeHashSql(namespaceSql)}), (${sortTimeSql}) DESC);
125
+ CREATE INDEX IF NOT EXISTS ${tableName}_logical_time_idx ON ${tableName} ((${sortTimeSql}) DESC);
95
126
  CREATE INDEX IF NOT EXISTS ${parentTableName}_parent_idx ON ${parentTableName} (parent_run_id, updated_at_ms DESC);
96
127
  CREATE INDEX IF NOT EXISTS ${leaseTableName}_expiry_idx ON ${leaseTableName} (expires_at_ms);
97
128
  CREATE INDEX IF NOT EXISTS ${journalTableName}_run_idx ON ${journalTableName} (run_key, updated_at_ms, tool_call_id)
@@ -104,53 +135,79 @@ export const createPostgresAgentRunStore = (options) => {
104
135
  await ensurePostgresTable(options.client, journalTableName, createJournalSql);
105
136
  await ensurePostgresTable(options.client, `${tableName}:indexes`, createIndexesSql);
106
137
  };
138
+ const physicalKey = async (runId, scope) => {
139
+ const targetScope = resolveScope(options.scope, scope);
140
+ const canonical = dbKey(runId, scope);
141
+ for (const key of [canonical, legacyScopedKey(targetScope, runId)]) {
142
+ const result = await options.client.query(`SELECT state_json FROM ${tableName} WHERE run_id = $1`, [key]);
143
+ const state = getRecordField(result.rows[0], ["state_json", "stateJson"]);
144
+ if (state && matchesRun(state, runId, targetScope))
145
+ return key;
146
+ if (state && key === canonical)
147
+ throw new ConflictError("Canonical agent key is occupied by a different legacy identity; migrate that identity before writing.");
148
+ }
149
+ return canonical;
150
+ };
151
+ const findByIdempotencyKey = async (idempotencyKey, scope) => {
152
+ const targetScope = resolveScope(options.scope, scope);
153
+ for (const key of [dbKey(idempotencyKey, scope), legacyScopedKey(targetScope, idempotencyKey)]) {
154
+ const result = await options.client.query(`SELECT runs.state_json FROM ${tableName} runs INNER JOIN ${idempotencyTableName} keys ON keys.run_id = runs.run_id WHERE keys.idempotency_key = $1`, [key]);
155
+ const state = getRecordField(result.rows[0], ["state_json", "stateJson"]);
156
+ if (state && state.idempotencyKey === idempotencyKey && matchesScope(state.scope, targetScope))
157
+ return normalizeAgentRunState(state);
158
+ if (state && key === dbKey(idempotencyKey, scope))
159
+ throw new ConflictError("Canonical idempotency key is occupied by a different legacy identity; migrate that index before writing.");
160
+ }
161
+ return undefined;
162
+ };
107
163
  return {
108
164
  async load(runId, scope) {
109
165
  await ensureAllTables();
110
- const result = await options.client.query(`SELECT state_json FROM ${tableName} WHERE run_id = $1`, [dbKey(runId, scope)]);
166
+ const result = await options.client.query(`SELECT state_json FROM ${tableName} WHERE run_id = $1`, [await physicalKey(runId, scope)]);
111
167
  const state = result.rows[0] ? (getRecordField(result.rows[0], ["state_json", "stateJson"]) ?? undefined) : undefined;
112
- return state ? normalizeAgentRunState(state) : undefined;
168
+ return state && matchesRun(state, runId, resolveScope(options.scope, scope)) ? normalizeAgentRunState(state) : undefined;
113
169
  },
114
170
  async findByIdempotencyKey(idempotencyKey, scope) {
115
171
  await ensureAllTables();
116
- const result = await options.client.query(`SELECT runs.state_json
117
- FROM ${tableName} runs
118
- INNER JOIN ${idempotencyTableName} keys ON keys.run_id = runs.run_id
119
- WHERE keys.idempotency_key = $1`, [dbKey(idempotencyKey, scope)]);
120
- const state = result.rows[0] ? (getRecordField(result.rows[0], ["state_json", "stateJson"]) ?? undefined) : undefined;
121
- return state ? normalizeAgentRunState(state) : undefined;
172
+ return findByIdempotencyKey(idempotencyKey, scope);
122
173
  },
123
174
  async findByParentRunId(parentRunId, scope) {
124
175
  await ensureAllTables();
125
- const result = await options.client.query(`SELECT runs.state_json
126
- FROM ${tableName} runs
127
- INNER JOIN ${parentTableName} parents ON parents.run_id = runs.run_id
128
- WHERE parents.parent_run_id = $1`, [dbKey(parentRunId, scope)]);
129
- return result.rows.flatMap((row) => {
130
- const state = getRecordField(row, ["state_json", "stateJson"]) ?? undefined;
131
- return state ? [normalizeAgentRunState(state)] : [];
132
- });
176
+ const targetScope = resolveScope(options.scope, scope);
177
+ const states = new Map();
178
+ for (const key of [dbKey(parentRunId, scope), legacyScopedKey(targetScope, parentRunId)]) {
179
+ const result = await options.client.query(`SELECT runs.state_json FROM ${tableName} runs INNER JOIN ${parentTableName} parents ON parents.run_id = runs.run_id WHERE parents.parent_run_id = $1`, [key]);
180
+ for (const row of result.rows) {
181
+ const state = getRecordField(row, ["state_json", "stateJson"]);
182
+ if (state && state.parentRunId === parentRunId && matchesScope(state.scope, targetScope))
183
+ states.set(state.runId, normalizeAgentRunState(state));
184
+ }
185
+ }
186
+ return [...states.values()];
133
187
  },
134
188
  async claimIdempotencyKey(state) {
135
189
  await ensureAllTables();
136
190
  const scope = resolveScope(options.scope, state.scope);
191
+ const existingOwner = await findByIdempotencyKey(state.idempotencyKey, scope);
192
+ if (existingOwner)
193
+ return { claimed: false, state: existingOwner };
137
194
  const normalized = normalizeAgentRunState({ ...state, ...(scope ? { scope } : {}) });
138
195
  const updatedAt = Date.now();
139
196
  await options.client.query(`INSERT INTO ${tableName} (run_id, state_json, updated_at_ms)
140
197
  VALUES ($1, $2::jsonb, $3)
141
- ON CONFLICT(run_id) DO NOTHING`, [dbKey(normalized.runId, scope), normalized, updatedAt]);
198
+ ON CONFLICT(run_id) DO NOTHING`, [await physicalKey(normalized.runId, scope), normalized, updatedAt]);
142
199
  const claim = await options.client.query(`INSERT INTO ${idempotencyTableName} (idempotency_key, run_id, updated_at_ms)
143
200
  VALUES ($1, $2, $3)
144
201
  ON CONFLICT(idempotency_key) DO NOTHING
145
- RETURNING run_id`, [dbKey(state.idempotencyKey, scope), dbKey(normalized.runId, scope), updatedAt]);
202
+ RETURNING run_id`, [dbKey(state.idempotencyKey, scope), await physicalKey(normalized.runId, scope), updatedAt]);
146
203
  const claimedRunId = getRecordField(claim.rows[0], ["run_id", "runId"]);
147
- if (claimedRunId === dbKey(normalized.runId, scope)) {
204
+ if (claimedRunId === await physicalKey(normalized.runId, scope)) {
148
205
  if (normalized.parentRunId) {
149
206
  await options.client.query(`INSERT INTO ${parentTableName} (run_id, parent_run_id, updated_at_ms)
150
207
  VALUES ($1, $2, $3)
151
208
  ON CONFLICT(run_id) DO UPDATE SET
152
209
  parent_run_id = EXCLUDED.parent_run_id,
153
- updated_at_ms = EXCLUDED.updated_at_ms`, [dbKey(normalized.runId, scope), dbKey(normalized.parentRunId, scope), updatedAt]);
210
+ updated_at_ms = EXCLUDED.updated_at_ms`, [await physicalKey(normalized.runId, scope), dbKey(normalized.parentRunId, scope), updatedAt]);
154
211
  }
155
212
  return { claimed: true, state: normalized };
156
213
  }
@@ -161,11 +218,11 @@ export const createPostgresAgentRunStore = (options) => {
161
218
  const existingState = existing.rows[0]
162
219
  ? getRecordField(existing.rows[0], ["state_json", "stateJson"])
163
220
  : undefined;
164
- if (!existingState) {
165
- throw new ConflictError("AgentRunState idempotency claim could not be loaded.");
221
+ if (!existingState || existingState.idempotencyKey !== state.idempotencyKey || !matchesScope(existingState.scope, scope)) {
222
+ throw new ConflictError("AgentRunState idempotency claim could not be loaded with the expected identity.");
166
223
  }
167
224
  if (existingState.runId !== normalized.runId) {
168
- await options.client.query(`DELETE FROM ${tableName} WHERE run_id = $1`, [dbKey(normalized.runId, scope)]);
225
+ await options.client.query(`DELETE FROM ${tableName} WHERE run_id = $1`, [await physicalKey(normalized.runId, scope)]);
169
226
  }
170
227
  return { claimed: false, state: normalizeAgentRunState(existingState) };
171
228
  },
@@ -176,9 +233,12 @@ export const createPostgresAgentRunStore = (options) => {
176
233
  const stored = { ...normalized, ...(scope ? { scope } : {}) };
177
234
  const updatedAt = Date.now();
178
235
  if (normalized.idempotencyKey) {
236
+ const existingOwner = await findByIdempotencyKey(normalized.idempotencyKey, scope);
237
+ if (existingOwner && existingOwner.runId !== normalized.runId)
238
+ throw new ConflictError("AgentRunState idempotency key conflict.");
179
239
  const owner = await options.client.query(`SELECT run_id FROM ${idempotencyTableName} WHERE idempotency_key = $1`, [dbKey(normalized.idempotencyKey, scope)]);
180
240
  const ownerRunId = getRecordField(owner.rows[0], ["run_id", "runId"]);
181
- if (typeof ownerRunId === "string" && ownerRunId !== dbKey(normalized.runId, scope)) {
241
+ if (typeof ownerRunId === "string" && ownerRunId !== await physicalKey(normalized.runId, scope)) {
182
242
  throw new ConflictError("AgentRunState idempotency key conflict.");
183
243
  }
184
244
  }
@@ -187,7 +247,7 @@ export const createPostgresAgentRunStore = (options) => {
187
247
  VALUES ($1, $2::jsonb, $3)
188
248
  ON CONFLICT(run_id) DO UPDATE SET
189
249
  state_json = EXCLUDED.state_json,
190
- updated_at_ms = EXCLUDED.updated_at_ms`, [dbKey(normalized.runId, scope), stored, updatedAt]);
250
+ updated_at_ms = EXCLUDED.updated_at_ms`, [await physicalKey(normalized.runId, scope), stored, updatedAt]);
191
251
  }
192
252
  else {
193
253
  const saved = await options.client.query(`INSERT INTO ${tableName} (run_id, state_json, updated_at_ms)
@@ -196,28 +256,28 @@ export const createPostgresAgentRunStore = (options) => {
196
256
  state_json = EXCLUDED.state_json,
197
257
  updated_at_ms = EXCLUDED.updated_at_ms
198
258
  WHERE COALESCE((${tableName}.state_json->>'revision')::bigint, 0) = $4
199
- RETURNING run_id`, [dbKey(normalized.runId, scope), stored, updatedAt, saveOptions.expectedRevision]);
200
- if (getRecordField(saved.rows[0], ["run_id", "runId"]) !== dbKey(normalized.runId, scope)) {
259
+ RETURNING run_id`, [await physicalKey(normalized.runId, scope), stored, updatedAt, saveOptions.expectedRevision]);
260
+ if (getRecordField(saved.rows[0], ["run_id", "runId"]) !== await physicalKey(normalized.runId, scope)) {
201
261
  throw new ConflictError("AgentRunState revision conflict.");
202
262
  }
203
263
  }
204
264
  if (normalized.idempotencyKey) {
205
265
  await options.client.query(`INSERT INTO ${idempotencyTableName} (idempotency_key, run_id, updated_at_ms)
206
266
  VALUES ($1, $2, $3)
207
- ON CONFLICT(idempotency_key) DO NOTHING`, [dbKey(normalized.idempotencyKey, scope), dbKey(normalized.runId, scope), updatedAt]);
267
+ ON CONFLICT(idempotency_key) DO NOTHING`, [dbKey(normalized.idempotencyKey, scope), await physicalKey(normalized.runId, scope), updatedAt]);
208
268
  }
209
- await options.client.query(`DELETE FROM ${parentTableName} WHERE run_id = $1`, [dbKey(normalized.runId, scope)]);
269
+ await options.client.query(`DELETE FROM ${parentTableName} WHERE run_id = $1`, [await physicalKey(normalized.runId, scope)]);
210
270
  if (normalized.parentRunId) {
211
271
  await options.client.query(`INSERT INTO ${parentTableName} (run_id, parent_run_id, updated_at_ms)
212
272
  VALUES ($1, $2, $3)
213
273
  ON CONFLICT(run_id) DO UPDATE SET
214
274
  parent_run_id = EXCLUDED.parent_run_id,
215
- updated_at_ms = EXCLUDED.updated_at_ms`, [dbKey(normalized.runId, scope), dbKey(normalized.parentRunId, scope), updatedAt]);
275
+ updated_at_ms = EXCLUDED.updated_at_ms`, [await physicalKey(normalized.runId, scope), dbKey(normalized.parentRunId, scope), updatedAt]);
216
276
  }
217
277
  },
218
278
  async delete(runId, scope) {
219
279
  await ensureAllTables();
220
- const key = dbKey(runId, scope);
280
+ const key = await physicalKey(runId, scope);
221
281
  await options.client.query(`WITH deleted_run AS (
222
282
  DELETE FROM ${tableName} WHERE run_id = $1 RETURNING run_id
223
283
  ), deleted_idempotency AS (
@@ -229,14 +289,63 @@ export const createPostgresAgentRunStore = (options) => {
229
289
  )
230
290
  DELETE FROM ${journalTableName} WHERE run_key = $1`, [key]);
231
291
  },
232
- async list(listOptions, scope) {
292
+ async list(listOptions = {}, scope) {
293
+ const targetScope = resolveScope(options.scope, scope);
294
+ const { limit, cursor } = parseAgentRunListOptions(listOptions);
295
+ const parameters = [];
296
+ const bind = (value) => { parameters.push(value); return `$${parameters.length}`; };
297
+ const predicates = [];
298
+ if (targetScope) {
299
+ for (const [expression, value] of [
300
+ [tenantSql, targetScope.tenantId],
301
+ [userSql, targetScope.userId],
302
+ [namespaceSql, targetScope.namespace]
303
+ ]) {
304
+ if (value === undefined) {
305
+ predicates.push(`${scopeHashSql(expression)} IS NULL`, `${expression} IS NULL`);
306
+ }
307
+ else {
308
+ const parameter = `${bind(value)}::text`;
309
+ predicates.push(`${scopeHashSql(expression)} = ${scopeHashSql(parameter)}`, `${expression} = ${parameter}`);
310
+ }
311
+ }
312
+ }
313
+ if (listOptions.agentId !== undefined)
314
+ predicates.push(`state_json->>'agentId' = ${bind(listOptions.agentId)}::text`);
315
+ if (listOptions.parentRunId !== undefined)
316
+ predicates.push(`state_json->>'parentRunId' = ${bind(listOptions.parentRunId)}::text`);
317
+ if (listOptions.statuses?.length)
318
+ predicates.push(`state_json->>'status' = ANY(${bind(listOptions.statuses)}::text[])`);
319
+ if (listOptions.updatedAfter !== undefined)
320
+ predicates.push(`${updatedTimeSql} > ${bind(listOptions.updatedAfter)}::double precision`);
321
+ if (listOptions.updatedBefore !== undefined)
322
+ predicates.push(`${updatedTimeSql} < ${bind(listOptions.updatedBefore)}::double precision`);
323
+ let cursorPredicate = "";
324
+ if (cursor) {
325
+ const utf16RunId = Array.from({ length: cursor[1].length }, (_, index) => cursor[1].charCodeAt(index).toString(16).padStart(4, "0")).join("");
326
+ const time = bind(cursor[0]);
327
+ const id = bind(utf16RunId);
328
+ cursorPredicate = cursor[2] === undefined
329
+ ? `WHERE (sort_time, run_id_sort) < (${time}::double precision, ${id}::text COLLATE "C")`
330
+ : `WHERE (sort_time, run_id_sort, scope_sort) < (${time}::double precision, ${id}::text COLLATE "C", ${bind(cursor[2])}::text COLLATE "C")`;
331
+ }
332
+ const query = `WITH candidates AS (
333
+ SELECT state_json, ${sortTimeSql} AS sort_time,
334
+ ${runIdSortSql} AS run_id_sort, ${scopedSortSql} AS scope_sort
335
+ FROM ${tableName}
336
+ ${predicates.length ? `WHERE ${predicates.join(" AND ")}` : ""}
337
+ )
338
+ SELECT state_json FROM candidates ${cursorPredicate}
339
+ ORDER BY sort_time DESC, run_id_sort DESC, scope_sort DESC
340
+ LIMIT ${bind(limit + 1)}::integer`;
233
341
  await ensureAllTables();
234
- const prefix = scopePrefix(resolveScope(options.scope, scope));
235
- const result = await options.client.query(`SELECT state_json FROM ${tableName} WHERE run_id >= $1 AND run_id < $2`, [prefix, `${prefix}\uffff`]);
342
+ const result = await options.client.query(query, parameters);
236
343
  const states = result.rows.flatMap((row) => {
237
344
  const state = getRecordField(row, ["state_json", "stateJson"]);
238
- return state ? [normalizeAgentRunState(state)] : [];
345
+ return state && (!targetScope || matchesScope(state.scope, targetScope)) ? [normalizeAgentRunState(state)] : [];
239
346
  });
347
+ // At most limit + 1 matching states cross the connection. Shared projection
348
+ // preserves exactly the same cursor format as memory, file and SQLite.
240
349
  return listStates(states, listOptions);
241
350
  },
242
351
  async deleteExpired(retention, scope) {
@@ -249,7 +358,7 @@ export const createPostgresAgentRunStore = (options) => {
249
358
  validateLeaseOptions(leaseOptions);
250
359
  await ensureAllTables();
251
360
  const now = leaseOptions.now ?? Date.now();
252
- const key = dbKey(runId, scope);
361
+ const key = await physicalKey(runId, scope);
253
362
  const expiresAt = now + leaseOptions.ttlMs;
254
363
  const result = await options.client.query(`INSERT INTO ${leaseTableName} (run_key, run_id, owner_id, expires_at_ms)
255
364
  SELECT $1, $2, $3, $4
@@ -270,20 +379,22 @@ export const createPostgresAgentRunStore = (options) => {
270
379
  const result = await options.client.query(`UPDATE ${leaseTableName}
271
380
  SET expires_at_ms = $3
272
381
  WHERE run_key = $1 AND owner_id = $2 AND expires_at_ms > $4
273
- RETURNING owner_id`, [dbKey(runId, scope), leaseOptions.ownerId, expiresAt, now]);
382
+ RETURNING owner_id`, [await physicalKey(runId, scope), leaseOptions.ownerId, expiresAt, now]);
274
383
  return getRecordField(result.rows[0], ["owner_id", "ownerId"]) === leaseOptions.ownerId
275
384
  ? { runId, ownerId: leaseOptions.ownerId, expiresAt }
276
385
  : undefined;
277
386
  },
278
387
  async releaseLease(runId, ownerId, scope) {
279
388
  await ensureAllTables();
280
- const result = await options.client.query(`DELETE FROM ${leaseTableName} WHERE run_key = $1 AND owner_id = $2 RETURNING owner_id`, [dbKey(runId, scope), ownerId]);
389
+ const result = await options.client.query(`DELETE FROM ${leaseTableName} WHERE run_key = $1 AND owner_id = $2 RETURNING owner_id`, [await physicalKey(runId, scope), ownerId]);
281
390
  return getRecordField(result.rows[0], ["owner_id", "ownerId"]) === ownerId;
282
391
  },
283
392
  async loadToolCall(runId, toolCallId, scope) {
284
393
  await ensureAllTables();
285
- const result = await options.client.query(`SELECT entry_json FROM ${journalTableName} WHERE run_key = $1 AND tool_call_id = $2`, [dbKey(runId, scope), toolCallId]);
394
+ const result = await options.client.query(`SELECT entry_json FROM ${journalTableName} WHERE run_key = $1 AND tool_call_id = $2`, [await physicalKey(runId, scope), toolCallId]);
286
395
  const entry = getRecordField(result.rows[0], ["entry_json", "entryJson"]);
396
+ if (entry && typeof entry === "object" && (!matchesRun(entry, runId, resolveScope(options.scope, scope)) || entry.toolCallId !== toolCallId))
397
+ throw new ConflictError("Persisted journal identity cannot be verified; reconcile or migrate before executing the tool.");
287
398
  return entry && typeof entry === "object" ? cloneJournalEntry(entry) : undefined;
288
399
  },
289
400
  async loadToolExecution(runId, toolCallId, scope) {
@@ -291,16 +402,20 @@ export const createPostgresAgentRunStore = (options) => {
291
402
  },
292
403
  async listToolCalls(runId, scope) {
293
404
  await ensureAllTables();
294
- const result = await options.client.query(`SELECT entry_json FROM ${journalTableName} WHERE run_key = $1 ORDER BY updated_at_ms, tool_call_id`, [dbKey(runId, scope)]);
405
+ const result = await options.client.query(`SELECT entry_json FROM ${journalTableName} WHERE run_key = $1 ORDER BY updated_at_ms, tool_call_id`, [await physicalKey(runId, scope)]);
295
406
  return result.rows.flatMap((row) => {
296
407
  const entry = getRecordField(row, ["entry_json", "entryJson"]);
408
+ if (entry && typeof entry === "object" && !matchesRun(entry, runId, resolveScope(options.scope, scope)))
409
+ throw new ConflictError("Persisted journal identity cannot be verified; reconcile or migrate before continuing.");
297
410
  return entry && typeof entry === "object" ? [cloneJournalEntry(entry)] : [];
298
411
  });
299
412
  },
300
413
  async saveToolCall(entry, journalOptions) {
301
414
  await ensureAllTables();
302
- const next = nextJournalEntry(entry, journalOptions);
303
- const key = dbKey(entry.runId, entry.scope);
415
+ await this.loadToolCall?.(entry.runId, entry.toolCallId, entry.scope);
416
+ const scope = resolveScope(options.scope, entry.scope);
417
+ const next = nextJournalEntry({ ...entry, ...(scope ? { scope } : {}) }, journalOptions);
418
+ const key = await physicalKey(entry.runId, entry.scope);
304
419
  const result = journalOptions?.expectedRevision === undefined
305
420
  ? await options.client.query(`INSERT INTO ${journalTableName} (run_key, tool_call_id, entry_json, revision, updated_at_ms)
306
421
  VALUES ($1, $2, $3::jsonb, $4, $5)
@@ -322,12 +437,13 @@ export const createPostgresAgentRunStore = (options) => {
322
437
  },
323
438
  async claimToolExecution(entry) {
324
439
  await ensureAllTables();
325
- const next = nextJournalEntry({ ...entry, status: "running", revision: 0 });
440
+ const scope = resolveScope(options.scope, entry.scope);
441
+ const next = nextJournalEntry({ ...entry, ...(scope ? { scope } : {}), status: "running", revision: 0 });
326
442
  const result = await options.client.query(`INSERT INTO ${journalTableName} (run_key, tool_call_id, entry_json, revision, updated_at_ms)
327
443
  SELECT $1, $2, $3::jsonb, 0, $4
328
444
  WHERE EXISTS (SELECT 1 FROM ${tableName} WHERE run_id = $1)
329
445
  ON CONFLICT(run_key, tool_call_id) DO NOTHING
330
- RETURNING entry_json`, [dbKey(entry.runId, entry.scope), entry.toolCallId, next, next.updatedAt]);
446
+ RETURNING entry_json`, [await physicalKey(entry.runId, entry.scope), entry.toolCallId, next, next.updatedAt]);
331
447
  const claimed = getRecordField(result.rows[0], ["entry_json", "entryJson"]);
332
448
  if (claimed && typeof claimed === "object")
333
449
  return { claimed: true, entry: next };
@@ -345,6 +461,9 @@ export const createPostgresAgentMemoryStore = (options) => {
345
461
  assertPostgresClient(options.client);
346
462
  const tableName = validateIdentifier(options.tableName ?? "zhivex_agent_memory", "tableName");
347
463
  const keyFor = (context) => (options.key ?? defaultMemoryKey)({ ...context, scope: resolveScope(options.scope, context.scope) });
464
+ const memoryContext = (context) => ({ ...context, scope: resolveScope(options.scope, context.scope) });
465
+ const encode = (context, messages) => options.key ? messages : encodeAgentMemory(memoryContext(context), messages);
466
+ const decode = (context, value) => options.key ? value : decodeAgentMemory(memoryContext(context), value);
348
467
  const selectMessages = options.selectMessages ?? defaultMemoryMessages;
349
468
  const createSql = `
350
469
  CREATE TABLE IF NOT EXISTS ${tableName} (
@@ -353,21 +472,36 @@ export const createPostgresAgentMemoryStore = (options) => {
353
472
  updated_at_ms BIGINT NOT NULL
354
473
  )
355
474
  `;
475
+ const assertMemoryIdentity = async (context) => {
476
+ if (options.key)
477
+ return;
478
+ const canonical = await options.client.query(`SELECT messages_json FROM ${tableName} WHERE memory_key = $1`, [keyFor(context)]);
479
+ if (canonical.rows.length) {
480
+ decode(context, getRecordField(canonical.rows[0], ["messages_json", "messagesJson"]));
481
+ return;
482
+ }
483
+ const legacy = legacyDefaultMemoryKey({ ...context, scope: resolveScope(options.scope, context.scope) });
484
+ const previous = await options.client.query(`SELECT messages_json FROM ${tableName} WHERE memory_key = $1`, [legacy]);
485
+ if (previous.rows.length)
486
+ throw new ValidationError(LEGACY_MEMORY_MIGRATION_MESSAGE);
487
+ };
356
488
  return {
357
489
  async load(context) {
358
490
  await ensurePostgresTable(options.client, tableName, createSql);
491
+ await assertMemoryIdentity(context);
359
492
  const result = await options.client.query(`SELECT messages_json FROM ${tableName} WHERE memory_key = $1`, [keyFor(context)]);
360
493
  return result.rows[0]
361
- ? (getRecordField(result.rows[0], ["messages_json", "messagesJson"]) ?? [])
494
+ ? decode(context, getRecordField(result.rows[0], ["messages_json", "messagesJson"]))
362
495
  : [];
363
496
  },
364
497
  async save(context) {
365
498
  await ensurePostgresTable(options.client, tableName, createSql);
499
+ await assertMemoryIdentity(context);
366
500
  await options.client.query(`INSERT INTO ${tableName} (memory_key, messages_json, updated_at_ms)
367
501
  VALUES ($1, $2::jsonb, $3)
368
502
  ON CONFLICT(memory_key) DO UPDATE SET
369
503
  messages_json = EXCLUDED.messages_json,
370
- updated_at_ms = EXCLUDED.updated_at_ms`, [keyFor(context), selectMessages(context.state), Date.now()]);
504
+ updated_at_ms = EXCLUDED.updated_at_ms`, [keyFor(context), encode(context, selectMessages(context.state)), Date.now()]);
371
505
  }
372
506
  };
373
507
  };