maka-agent 0.2.0-dev.42.20260918 → 0.2.0-dev.44.20260920

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 (59) hide show
  1. package/LICENSE +12 -6
  2. package/dist/acp/maka-acp-agent.js +17 -6
  3. package/dist/acp/session-event-mapper.js +6 -0
  4. package/dist/acp/session-interactions.js +520 -0
  5. package/dist/acp/session-registry.js +80 -9
  6. package/dist/acp/tool-event-mapper.js +60 -2
  7. package/dist/mcp-capability-provider.js +7 -0
  8. package/dist/pi-tui-runner.js +57 -6
  9. package/dist/runtime-host-tui-command.js +1 -1
  10. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  11. package/node_modules/@maka/core/dist/chat-model-choice.js +3 -0
  12. package/node_modules/@maka/core/dist/connection-usage.js +27 -0
  13. package/node_modules/@maka/core/dist/external-session.js +4 -3
  14. package/node_modules/@maka/core/dist/llm-connections.js +3 -21
  15. package/node_modules/@maka/core/dist/model-catalog.js +8 -20
  16. package/node_modules/@maka/core/dist/model-metadata.generated.js +304 -304
  17. package/node_modules/@maka/core/dist/model-thinking.js +16 -1
  18. package/node_modules/@maka/core/dist/models-dev-projection.js +0 -1
  19. package/node_modules/@maka/core/dist/provider-auth.js +9 -1
  20. package/node_modules/@maka/core/dist/provider-registry.js +7 -51
  21. package/node_modules/@maka/core/dist/runtime-policy/connection-catalog-codec.js +7 -0
  22. package/node_modules/@maka/core/dist/runtime-policy/model-catalog-entry-codec.js +14 -1
  23. package/node_modules/@maka/core/dist/settings.js +2 -3
  24. package/node_modules/@maka/core/dist/skill-locations.js +29 -0
  25. package/node_modules/@maka/core/package.json +2 -0
  26. package/node_modules/@maka/mcp/dist/index.js +22 -0
  27. package/node_modules/@maka/mcp/dist/oauth.js +4 -2
  28. package/node_modules/@maka/mcp/dist/tool-progress.js +45 -0
  29. package/node_modules/@maka/runtime/dist/commandcode-cli-language-model.js +27 -3
  30. package/node_modules/@maka/runtime/dist/connection-usage.js +232 -0
  31. package/node_modules/@maka/runtime/dist/opencode-session-header.js +2 -3
  32. package/node_modules/@maka/runtime/dist/session-manager.js +1 -44
  33. package/node_modules/@maka/runtime/dist/skills-discovery.js +17 -23
  34. package/node_modules/@maka/runtime/dist/test-connection.js +3 -66
  35. package/node_modules/@maka/runtime/package.json +1 -0
  36. package/node_modules/@maka/runtime-host/dist/client/client-capability-channel.js +44 -9
  37. package/node_modules/@maka/runtime-host/dist/client/index.js +1 -1
  38. package/node_modules/@maka/runtime-host/dist/client/session-subscription.js +33 -3
  39. package/node_modules/@maka/runtime-host/dist/protocol/connection-effects.js +132 -1
  40. package/node_modules/@maka/runtime-host/dist/protocol/index.js +13 -3
  41. package/node_modules/@maka/runtime-host/dist/protocol/message.js +10 -0
  42. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +1 -1
  43. package/node_modules/@maka/runtime-host/dist/protocol/session-catalog.js +1 -1
  44. package/node_modules/@maka/runtime-host/dist/protocol/turn.js +0 -33
  45. package/node_modules/@maka/runtime-host/dist/server/access-credential-store.js +2 -0
  46. package/node_modules/@maka/runtime-host/dist/server/bootstrap-runtime-policy.js +31 -104
  47. package/node_modules/@maka/runtime-host/dist/server/connection-effect-coordinator.js +57 -1
  48. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +4 -5
  49. package/node_modules/@maka/runtime-host/dist/server/interactive-turn-coordinator.js +1 -16
  50. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +46 -28
  51. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +5 -16
  52. package/node_modules/@maka/runtime-host/dist/server/session-catalog-coordinator.js +21 -12
  53. package/node_modules/@maka/runtime-host/dist/server/session-turn-access-request-coordinator.js +7 -17
  54. package/node_modules/@maka/storage/dist/codex-session-adapter.js +26 -28
  55. package/node_modules/@maka/storage/dist/runtime-policy/connection-catalog-document.js +0 -62
  56. package/node_modules/@maka/storage/dist/runtime-policy/coordinator.js +34 -4
  57. package/node_modules/@maka/storage/dist/runtime-policy-stores.js +2 -1
  58. package/node_modules/@maka/storage/dist/session-store.js +5 -2
  59. package/package.json +1 -1
@@ -26,19 +26,16 @@ const EMPTY_SKILL_INVOCATION = {
26
26
  failed: [],
27
27
  receipts: [],
28
28
  };
29
- /** Owns Interactive Turn start and regenerate wire semantics. */
29
+ /** Owns Interactive Turn start wire semantics. */
30
30
  export class HostInteractiveTurnCoordinator {
31
31
  handlers = {
32
32
  'turn.start': (input, context) => this.#start(input, context),
33
- 'turn.regenerate': (input, context) => this.#regenerate(input, context),
34
33
  };
35
34
  #executions;
36
35
  #turns;
37
- #runtime;
38
36
  constructor(options) {
39
37
  this.#executions = options.executions;
40
38
  this.#turns = options.turns;
41
- this.#runtime = options.runtime;
42
39
  }
43
40
  async #start(input, context) {
44
41
  const content = normalizeMessageContent(input.content);
@@ -128,18 +125,6 @@ export class HostInteractiveTurnCoordinator {
128
125
  },
129
126
  };
130
127
  }
131
- #regenerate(input, context) {
132
- if (input.sourceTurnId === input.turnId) {
133
- return Promise.resolve(operationConflict('Regenerate source and target Turn identities must differ'));
134
- }
135
- return this.#executions.startInteractiveRootMessage({
136
- sessionId: input.sessionId,
137
- turnId: input.turnId,
138
- execution: { kind: 'regenerate', sourceTurnId: input.sourceTurnId },
139
- archivedMessage: 'Cannot regenerate a Turn in an archived Session',
140
- prepareContent: async () => (await this.#runtime.prepareRegenerateTurn(input.sessionId, input.sourceTurnId)).content,
141
- }, context);
142
- }
143
128
  }
144
129
  function rejected(message) {
145
130
  return { kind: 'rejected', outcome: operationConflict(message) };
@@ -107,35 +107,53 @@ export class HostMessageCoordinator {
107
107
  }
108
108
  return success({ cancelledMessageIds });
109
109
  }
110
- async queryMessageExecutions(input) {
111
- const resolutions = [];
112
- for (const messageId of input.messageIds) {
113
- const disposition = await this.#resolveMessageExecution(input.sessionId, messageId);
114
- if (disposition.kind === 'owned_root' || disposition.kind === 'shared_turn') {
115
- // This read projects current execution, including safe-boundary
116
- // continuations. The Message's durable admission ownership is unchanged.
117
- const latest = await this.#root.readLatestRootTurnLineage({
118
- sessionId: input.sessionId,
119
- turnId: disposition.turnId,
120
- runId: disposition.runId,
121
- });
122
- resolutions.push({
123
- messageId,
124
- state: 'owned',
125
- turnId: latest.turnId,
126
- runId: latest.runId,
127
- });
128
- continue;
129
- }
130
- if (disposition.kind === 'cancelled') {
131
- resolutions.push({ messageId, state: 'cancelled' });
132
- continue;
133
- }
134
- if (disposition.kind === 'pending') {
135
- resolutions.push({ messageId, state: 'pending' });
110
+ queryMessageExecutions(input) {
111
+ // Enter the Session admission the way every other admission reader does.
112
+ // `not_admitted` claims that no epoch ever admitted this identity, and it
113
+ // is only sound while no admission write can be in flight. WorkHub writes
114
+ // admission rows without an in-memory submit to observe, so the gate —
115
+ // not `#pendingSubmits` alone — is what makes the read atomic.
116
+ return this.#sessionAdmission.runOrJoin(input.sessionId, async () => {
117
+ const resolutions = [];
118
+ for (const messageId of input.messageIds) {
119
+ const disposition = await this.#resolveMessageExecution(input.sessionId, messageId);
120
+ if (disposition.kind === 'owned_root' || disposition.kind === 'shared_turn') {
121
+ // This read projects current execution, including safe-boundary
122
+ // continuations. The Message's durable admission ownership is unchanged.
123
+ const latest = await this.#root.readLatestRootTurnLineage({
124
+ sessionId: input.sessionId,
125
+ turnId: disposition.turnId,
126
+ runId: disposition.runId,
127
+ });
128
+ resolutions.push({
129
+ messageId,
130
+ state: 'owned',
131
+ turnId: latest.turnId,
132
+ runId: latest.runId,
133
+ });
134
+ continue;
135
+ }
136
+ if (disposition.kind === 'cancelled') {
137
+ resolutions.push({ messageId, state: 'cancelled' });
138
+ continue;
139
+ }
140
+ if (disposition.kind === 'pending') {
141
+ resolutions.push({ messageId, state: 'pending' });
142
+ continue;
143
+ }
144
+ // `recovering` means no durable receipt, steering proof, cancellation
145
+ // tombstone, or pending admission names this identity. Under the
146
+ // Session gate no admission write is in flight, so that silence is
147
+ // itself the proof: nothing in this epoch — or any prior one, since a
148
+ // stale epoch's submit can never commit here — ever admitted it.
149
+ // Report that fact positively instead of omitting the identity, so a
150
+ // missing entry stops meaning both "not admitted" and "cannot say yet".
151
+ if (this.#pendingSubmits.has(operationKey(input.sessionId, messageId)))
152
+ continue;
153
+ resolutions.push({ messageId, state: 'not_admitted' });
136
154
  }
137
- }
138
- return success({ resolutions });
155
+ return success({ resolutions });
156
+ });
139
157
  }
140
158
  /**
141
159
  * Cancels exactly one durable pending Message, or returns the Turn that has
@@ -27,7 +27,7 @@ import { decodeSkillInvocationResult, } from '@maka/core/skill-invocation';
27
27
  import { agentGraphIdForRootSession } from '@maka/runtime/stream-graph-coordinator';
28
28
  import { RuntimeHostedRootConflictError, RuntimeHostedRootUnavailableError, RuntimeMessageAuthorityInvariantError, } from '@maka/runtime/message-authority';
29
29
  import { isShutdownCancelledInteractionAdmission, RuntimeInteractionAdmissionRejectedError, RuntimeInteractionFailStopError, RuntimeInteractionInvariantError, } from '@maka/runtime/interaction-authority';
30
- import { normalizeStopSessionSource, RuntimeRegenerateTurnError, } from '@maka/runtime/session-manager';
30
+ import { normalizeStopSessionSource, } from '@maka/runtime/session-manager';
31
31
  import { RuntimeOwnerCleanupError } from '@maka/runtime/runtime-kernel';
32
32
  import { parseSkillInvocationTokens, } from '@maka/runtime/skill-invocation';
33
33
  import { skillInvocationInlineReferences } from '@maka/runtime/skill-invocation-receipt';
@@ -1422,21 +1422,10 @@ export class RootTurnCoordinator {
1422
1422
  return { kind: 'ready', content: request.content };
1423
1423
  if ('prepareFreshContent' in request)
1424
1424
  return request.prepareFreshContent(lease);
1425
- try {
1426
- return {
1427
- kind: 'ready',
1428
- content: normalizeMessageContent(await request.prepareContent()),
1429
- };
1430
- }
1431
- catch (error) {
1432
- if (error instanceof RuntimeRegenerateTurnError) {
1433
- return {
1434
- kind: 'rejected',
1435
- outcome: error.code === 'not_found' ? notFound(error.message) : operationConflict(error.message),
1436
- };
1437
- }
1438
- throw error;
1439
- }
1425
+ return {
1426
+ kind: 'ready',
1427
+ content: normalizeMessageContent(await request.prepareContent()),
1428
+ };
1440
1429
  }
1441
1430
  async queryTurnResume(input, context) {
1442
1431
  if (isWorkHubCoordinationSessionId(input.sessionId)) {
@@ -21,7 +21,7 @@ import { RuntimeHostProtocolError } from '../protocol/errors.js';
21
21
  import { createHash } from 'node:crypto';
22
22
  import { authorizeConnectionModel, connectionEnabledModelIds } from '@maka/core/llm-connections';
23
23
  import { isModelExplicitlyUnsupportedForChat } from '@maka/core/model-catalog';
24
- import { thinkingVariantsForConnection } from '@maka/core/model-thinking';
24
+ import { defaultThinkingLevelForConnection, thinkingVariantsForConnection, } from '@maka/core/model-thinking';
25
25
  import { executionBoundaryDisplayMode, } from '@maka/core/sandbox-boundary';
26
26
  import { isExecutorId } from '@maka/core/executor-id';
27
27
  import { DEFAULT_SESSION_NAME, normalizeUserSessionName } from '@maka/core/session-name';
@@ -184,7 +184,7 @@ export class HostSessionCatalogCoordinator {
184
184
  */
185
185
  async resolveDefaultCreateTarget() {
186
186
  try {
187
- return await this.#composeCreateTarget(this.#resolveModel({ kind: 'default' }, undefined));
187
+ return await this.#composeCreateTarget(this.#resolveModel({ kind: 'default' }, undefined, true));
188
188
  }
189
189
  catch (error) {
190
190
  if (error instanceof SessionOperationFailure &&
@@ -200,6 +200,7 @@ export class HostSessionCatalogCoordinator {
200
200
  llmConnectionId: model.connectionId,
201
201
  llmConnectionSlug: model.connectionSlug,
202
202
  model: model.model,
203
+ ...(model.thinkingLevel === undefined ? {} : { thinkingLevel: model.thinkingLevel }),
203
204
  permissionMode: policy.policy.chatDefaults.permissionMode,
204
205
  toolMode: policy.policy.chatDefaults.codeModeEnabled ? 'code_mode' : 'direct',
205
206
  collaborationMode: 'agent',
@@ -235,7 +236,7 @@ export class HostSessionCatalogCoordinator {
235
236
  ...(model.connectionId ? { llmConnectionId: model.connectionId } : {}),
236
237
  llmConnectionSlug: model.connectionSlug,
237
238
  model: model.model,
238
- ...(input.thinkingLevel === undefined ? {} : { thinkingLevel: input.thinkingLevel }),
239
+ ...(model.thinkingLevel === undefined ? {} : { thinkingLevel: model.thinkingLevel }),
239
240
  ...(input.toolProfile === undefined ? {} : { toolProfile: input.toolProfile }),
240
241
  permissionMode: prepared.permissionMode ?? policy.policy.chatDefaults.permissionMode,
241
242
  toolMode: policy.policy.chatDefaults.codeModeEnabled ? 'code_mode' : 'direct',
@@ -405,7 +406,7 @@ export class HostSessionCatalogCoordinator {
405
406
  ...(model.connectionId ? { llmConnectionId: model.connectionId } : {}),
406
407
  llmConnectionSlug: model.connectionSlug,
407
408
  model: model.model,
408
- ...(input.thinkingLevel === undefined ? {} : { thinkingLevel: input.thinkingLevel }),
409
+ ...(model.thinkingLevel === undefined ? {} : { thinkingLevel: model.thinkingLevel }),
409
410
  ...(input.toolProfile === undefined ? {} : { toolProfile: input.toolProfile }),
410
411
  permissionMode: prepared.permissionMode ?? policy.policy.chatDefaults.permissionMode,
411
412
  toolMode: toolMode ?? (policy.policy.chatDefaults.codeModeEnabled ? 'code_mode' : 'direct'),
@@ -715,7 +716,7 @@ export class HostSessionCatalogCoordinator {
715
716
  connectionId: candidate.connectionId,
716
717
  connectionSlug: candidate.connectionSlug,
717
718
  model: candidate.modelId,
718
- }, undefined);
719
+ }, undefined, true);
719
720
  }
720
721
  catch (error) {
721
722
  if (!(error instanceof SessionOperationFailure))
@@ -741,7 +742,7 @@ export class HostSessionCatalogCoordinator {
741
742
  }
742
743
  throw new NoUsableImportModelError('No usable Session model connection is available for import');
743
744
  }
744
- async #resolveModel(target, thinkingLevel) {
745
+ async #resolveModel(target, thinkingLevel, applyConfiguredDefault = false) {
745
746
  const selected = await this.#selectModelTarget(target);
746
747
  const readiness = await this.#runtimePolicy.operations.resolveExecutionConnection({
747
748
  kind: 'bound',
@@ -788,17 +789,25 @@ export class HostSessionCatalogCoordinator {
788
789
  // rejected — execution-model-authority rebuilds the runtime connection
789
790
  // from the same table, so whatever passes here is exactly what the wire
790
791
  // can send.
791
- if (thinkingLevel !== undefined &&
792
+ const resolvedThinkingLevel = thinkingLevel ??
793
+ (applyConfiguredDefault
794
+ ? defaultThinkingLevelForConnection({
795
+ providerType: connection.providerType,
796
+ modelOverrides: connection.modelOverrides,
797
+ }, selected.modelId)
798
+ : undefined);
799
+ if (resolvedThinkingLevel !== undefined &&
792
800
  !thinkingVariantsForConnection({
793
801
  providerType: connection.providerType,
794
802
  modelOverrides: connection.modelOverrides,
795
- }, selected.modelId).includes(thinkingLevel)) {
796
- throw new SessionOperationFailure('invalid_request', `Session model does not support thinking level ${thinkingLevel}`);
803
+ }, selected.modelId).includes(resolvedThinkingLevel)) {
804
+ throw new SessionOperationFailure('invalid_request', `Session model does not support thinking level ${resolvedThinkingLevel}`);
797
805
  }
798
806
  return {
799
807
  connectionId: connection.connectionId,
800
808
  connectionSlug: connection.slug,
801
809
  model: selected.modelId,
810
+ thinkingLevel: resolvedThinkingLevel,
802
811
  };
803
812
  }
804
813
  async #selectModelTarget(target) {
@@ -888,7 +897,7 @@ export class HostSessionCatalogCoordinator {
888
897
  if (!input.modelTarget) {
889
898
  throw new SessionOperationFailure('invalid_request', 'Session creation requires a model target or executor id');
890
899
  }
891
- return await this.#resolveModel(input.modelTarget, input.thinkingLevel);
900
+ return await this.#resolveModel(input.modelTarget, input.thinkingLevel ?? undefined, input.thinkingLevel !== null);
892
901
  }
893
902
  async #readRuntimePolicy() {
894
903
  try {
@@ -943,7 +952,7 @@ async function prepareCreate(input) {
943
952
  }
944
953
  function createRequestFingerprint(input, prepared) {
945
954
  const identity = [
946
- 'session.create.v4',
955
+ 'session.create.v5',
947
956
  input.sessionId,
948
957
  input.workspace.kind === 'project'
949
958
  ? ['project', input.workspace.projectId]
@@ -960,7 +969,7 @@ function createRequestFingerprint(input, prepared) {
960
969
  input.modelTarget.connectionSlug,
961
970
  input.modelTarget.model,
962
971
  ],
963
- input.thinkingLevel ?? null,
972
+ input.thinkingLevel === undefined ? ['model_default'] : input.thinkingLevel,
964
973
  input.toolProfile ?? null,
965
974
  prepared.permissionMode ?? ['runtime_default'],
966
975
  input.collaborationMode ?? 'agent',
@@ -19,7 +19,6 @@
19
19
  export class SessionTurnAccessRequestCoordinator {
20
20
  #authority;
21
21
  #startTurn;
22
- #regenerateTurn;
23
22
  #acquireResidency;
24
23
  #requestDrain;
25
24
  #whenIdle;
@@ -30,7 +29,6 @@ export class SessionTurnAccessRequestCoordinator {
30
29
  constructor(input) {
31
30
  this.#authority = input.authority;
32
31
  this.#startTurn = input.startTurn;
33
- this.#regenerateTurn = input.regenerateTurn;
34
32
  this.#acquireResidency = input.acquireResidency;
35
33
  this.#requestDrain = input.requestDrain;
36
34
  this.#whenIdle = input.whenIdle;
@@ -98,21 +96,13 @@ export class SessionTurnAccessRequestCoordinator {
98
96
  async #run(request, context) {
99
97
  for (;;) {
100
98
  try {
101
- if ('content' in request.intent) {
102
- const outcome = await this.#startTurn(request.intent, context);
103
- if (outcome.ok)
104
- return outcome.result.kind;
105
- if (outcome.error.code !== 'session_busy') {
106
- return this.#draining ? undefined : 'failed';
107
- }
108
- }
109
- else {
110
- const outcome = await this.#regenerateTurn(request.intent, context);
111
- if (outcome.ok)
112
- return 'started';
113
- if (outcome.error.code !== 'session_busy') {
114
- return this.#draining ? undefined : 'failed';
115
- }
99
+ if (!('content' in request.intent))
100
+ return 'failed';
101
+ const outcome = await this.#startTurn(request.intent, context);
102
+ if (outcome.ok)
103
+ return outcome.result.kind;
104
+ if (outcome.error.code !== 'session_busy') {
105
+ return this.#draining ? undefined : 'failed';
116
106
  }
117
107
  }
118
108
  catch {
@@ -16,6 +16,7 @@
16
16
  * specific language governing permissions and limitations
17
17
  * under the License.
18
18
  */
19
+ import { createHash } from 'node:crypto';
19
20
  import { open, opendir, readdir, realpath, stat } from 'node:fs/promises';
20
21
  import { homedir } from 'node:os';
21
22
  import { basename, join, resolve, sep } from 'node:path';
@@ -29,6 +30,7 @@ const CODEX_ROLLOUT_READ_BYTES = 64 * 1024;
29
30
  const CODEX_ROLLOUT_MAX_RECORD_BYTES = 64 * 1024 * 1024;
30
31
  const CODEX_ROLLOUT_MAX_CONVERTED_BYTES = 256 * 1024 * 1024;
31
32
  const CODEX_ROLLOUT_MAX_MESSAGES = 250_000;
33
+ const CODEX_EPOCH_MS_SQL_FUNCTION = 'maka_codex_epoch_ms';
32
34
  const CODEX_SESSION_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
33
35
  const CODEX_SUPPORTED_THREAD_SOURCES = ['cli', 'exec', 'vscode', 'atlas', 'chatgpt'];
34
36
  const CODEX_UNSAFE_PATH_CHARS = /[\u0000-\u001F\u007F\u0080-\u009F\u061C\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u2069\uFEFF]/;
@@ -176,6 +178,7 @@ export class CodexSessionAdapter {
176
178
  try {
177
179
  const sqlite = await import('node:sqlite');
178
180
  db = new sqlite.DatabaseSync(dbPath, { readOnly: true });
181
+ registerCodexEpochNormalization(db);
179
182
  const spec = codexThreadQuery(db, query, undefined, keyset);
180
183
  if (!spec)
181
184
  return undefined;
@@ -707,6 +710,7 @@ async function readCodexThreadRows(dbPath, query, exactId) {
707
710
  const sqlite = await import('node:sqlite');
708
711
  const db = new sqlite.DatabaseSync(dbPath, { readOnly: true });
709
712
  try {
713
+ registerCodexEpochNormalization(db);
710
714
  const spec = codexThreadQuery(db, query, exactId);
711
715
  if (!spec)
712
716
  return undefined;
@@ -753,22 +757,11 @@ function codexThreadQuery(db, query, exactId, keyset) {
753
757
  // No cwd clause. SQLite cannot express the matcher's cross-platform path
754
758
  // equivalence, so the shared matcher remains the only workspace authority.
755
759
  const orderColumns = ['updated_at_ms', 'updated_at', 'created_at_ms', 'created_at'].filter((column) => columns.has(column));
756
- // One authority for the ordering key. It is computed here, selected as
757
- // `sort_key`, and read straight back off the row to build the cursor, so the
758
- // position a cursor names is by construction the position the query ordered
759
- // by. Recomputing it in JS let the two drift on a stored TEXT value: SQL
760
- // keeps the text as the key and orders it above every number, while the JS
761
- // fallback chain skips that column and lands on a different one. A TEXT key
762
- // never satisfies a numeric comparison, so the disagreement did not surface
763
- // as a duplicate — it ended the traversal at that page and dropped every
764
- // Conversation after it without an error. Casting first also keeps the key
765
- // numeric, which is what the cursor's 8-byte encoding requires.
766
- const orderValues = orderColumns.map((column) => {
767
- const numeric = `CAST(${column} AS REAL)`;
768
- return column.endsWith('_ms')
769
- ? numeric
770
- : `(CASE WHEN ${numeric} >= 1000000000000 THEN ${numeric} ELSE ${numeric} * 1000 END)`;
771
- });
760
+ // The same normalizer owns displayed timestamps and this SQL ordering key.
761
+ // Selecting the key with the row then makes the cursor name exactly the
762
+ // position the query used, including ISO text stored in an INTEGER-affinity
763
+ // column.
764
+ const orderValues = orderColumns.map((column) => `${CODEX_EPOCH_MS_SQL_FUNCTION}(${column})`);
772
765
  const orderExpression = orderValues.length > 0 ? `coalesce(${orderValues.join(', ')}, 0)` : '0';
773
766
  if (keyset) {
774
767
  where.push(`(${orderExpression} < ? OR (${orderExpression} = ? AND id < ?))`);
@@ -797,6 +790,9 @@ function finiteNumber(value) {
797
790
  }
798
791
  return undefined;
799
792
  }
793
+ function registerCodexEpochNormalization(db) {
794
+ db.function(CODEX_EPOCH_MS_SQL_FUNCTION, { deterministic: true, directOnly: true }, (value) => normalizeEpochMs(value) ?? null);
795
+ }
800
796
  async function codexStateDbsNewestFirst(codexHome) {
801
797
  try {
802
798
  const root = await realpath(codexHome);
@@ -835,9 +831,10 @@ async function* iterateRolloutFiles(root, archived, relativeRoot = '') {
835
831
  entry.name.startsWith('rollout-') &&
836
832
  entry.name.endsWith('.jsonl')) {
837
833
  try {
834
+ const catalogKey = `${archived ? 'a' : 's'}/${relativePath}`;
838
835
  yield {
839
836
  path,
840
- catalogKey: `${archived ? 'a' : 's'}/${relativePath}`,
837
+ catalogIdentity: createHash('sha256').update(catalogKey).digest('base64url'),
841
838
  mtimeMs: (await stat(path)).mtimeMs,
842
839
  archived,
843
840
  };
@@ -893,23 +890,27 @@ async function nextRolloutCatalogBatch(codexHome, query, keyset, limit, maxCandi
893
890
  return page;
894
891
  }
895
892
  function compareRolloutCandidates(left, right) {
896
- return right.mtimeMs - left.mtimeMs || left.catalogKey.localeCompare(right.catalogKey);
893
+ return right.mtimeMs - left.mtimeMs || left.catalogIdentity.localeCompare(right.catalogIdentity);
897
894
  }
898
895
  function rolloutCandidateIsAfter(candidate, keyset) {
899
896
  return (compareRolloutCandidates(candidate, {
900
897
  mtimeMs: keyset.mtimeMs,
901
- catalogKey: keyset.pathKey,
898
+ catalogIdentity: keyset.pathIdentity,
902
899
  }) > 0);
903
900
  }
904
901
  function candidateKeyset(candidate) {
905
- return { kind: 'filesystem', mtimeMs: candidate.mtimeMs, pathKey: candidate.catalogKey };
902
+ return {
903
+ kind: 'filesystem',
904
+ mtimeMs: candidate.mtimeMs,
905
+ pathIdentity: candidate.catalogIdentity,
906
+ };
906
907
  }
907
908
  function encodeCatalogKeyset(query, keyset) {
908
909
  const queryHash = externalSessionCatalogQueryHash(query);
909
910
  if (keyset.kind === 'database') {
910
911
  return `d:${queryHash}:${Buffer.from(keyset.stateDatabase).toString('base64url')}:${encodeCursorNumber(keyset.sortTimestamp)}:${Buffer.from(keyset.id).toString('base64url')}`;
911
912
  }
912
- return `f:${queryHash}:${encodeCursorNumber(keyset.mtimeMs)}:${Buffer.from(keyset.pathKey).toString('base64url')}`;
913
+ return `f2:${queryHash}:${encodeCursorNumber(keyset.mtimeMs)}:${keyset.pathIdentity}`;
913
914
  }
914
915
  function decodeCatalogKeyset(cursor, query) {
915
916
  if (cursor === undefined)
@@ -935,18 +936,15 @@ function decodeCatalogKeyset(cursor, query) {
935
936
  }
936
937
  return { kind: 'database', stateDatabase, sortTimestamp, id };
937
938
  }
938
- if (parts[0] === 'f') {
939
+ if (parts[0] === 'f2') {
939
940
  if (parts.length !== 4)
940
941
  throw new ExternalSessionCatalogCursorError();
941
942
  const mtimeMs = decodeCursorNumber(parts[2]);
942
- const encodedPathKey = parts[3];
943
- const pathKey = Buffer.from(encodedPathKey, 'base64url').toString('utf8');
944
- if (Buffer.byteLength(pathKey, 'utf8') > 320 ||
945
- Buffer.from(pathKey).toString('base64url') !== encodedPathKey ||
946
- !/^[as]\/[^\u0000-\u001f\u007f]+$/.test(pathKey)) {
943
+ const pathIdentity = parts[3];
944
+ if (!/^[A-Za-z0-9_-]{43}$/.test(pathIdentity)) {
947
945
  throw new ExternalSessionCatalogCursorError();
948
946
  }
949
- return { kind: 'filesystem', mtimeMs, pathKey };
947
+ return { kind: 'filesystem', mtimeMs, pathIdentity };
950
948
  }
951
949
  throw new ExternalSessionCatalogCursorError();
952
950
  }
@@ -26,7 +26,6 @@ import { CONNECTION_CATALOG_MAX_CONNECTIONS, decodeCanonicalConnectionCatalogEnt
26
26
  import { PROVIDER_REGISTRY, reconcileConnectionAfterModelFetch } from '@maka/core/llm-connections';
27
27
  import { modelIdAliasesForProvider, providerReportsCompleteModelCatalog, } from '@maka/core/model-metadata';
28
28
  import { isRetiredProvider } from '@maka/core/provider-registry';
29
- import { pruneModelOverrides } from '@maka/core/model-thinking';
30
29
  import { deepFreeze, nextRevision, record, revision, unique } from './codec.js';
31
30
  import { codecError, decodeConnectionInput, decodePersistedDomain, RuntimePolicyStoreError, } from './errors.js';
32
31
  import { CATALOG_DOCUMENT_MAX_BYTES, readBoundedJsonDocument, serializeJsonDocument, writeJsonDocument, } from './document-io.js';
@@ -285,67 +284,6 @@ export class ConnectionCatalogDocumentOwner {
285
284
  await this.write(root, next);
286
285
  return committed(next);
287
286
  }
288
- /**
289
- * Built-in seed evolution as ONE atomic catalog mutation. A row whose
290
- * `enabledModelIds` still exactly match a historical system seed is provably
291
- * system-owned: it follows the current seed, its static inventory is
292
- * re-derived from the current build, and a default target the migration
293
- * removes is retargeted inside the same document write — so no restart can
294
- * observe enabled ids without their inventory, or a nulled default awaiting
295
- * a second write. Any other inventory (including a reordering) is a user
296
- * selection and is never touched; an already-null default stays null.
297
- */
298
- async migrateSystemSeed(root, input) {
299
- if (!input.enabledModelIds.includes(input.defaultModelId)) {
300
- throw codecError('invalid_connection_input', 'Seed default must be in the seed selection');
301
- }
302
- const current = await this.read(root);
303
- const index = current.connections.findIndex((item) => item.slug === input.slug && item.providerType === input.providerType);
304
- const previous = current.connections[index];
305
- const retired = new Set(input.retiredModelIds);
306
- const sameIds = (left, right) => left.length === right.length && left.every((id, position) => id === right[position]);
307
- const isLegacySeed = previous
308
- ? input.legacyEnabledModelIds.some((seed) => sameIds(previous.enabledModelIds, seed))
309
- : false;
310
- const hasRetiredModels = previous
311
- ? previous.enabledModelIds.some((id) => retired.has(id)) ||
312
- previous.models.some((model) => retired.has(model.id))
313
- : false;
314
- if (!previous || (!isLegacySeed && !hasRetiredModels)) {
315
- return committed(current);
316
- }
317
- // A legacy seed's stored inventory was the registry's shipped list copied
318
- // in at write time. Clearing it is the migration: the resolver prepends
319
- // that list from the current build, so the row stops carrying a stale
320
- // second copy of it. Any other row keeps its own inventory, minus the
321
- // retired ids.
322
- const models = isLegacySeed ? [] : previous.models.filter((model) => !retired.has(model.id));
323
- const { lastTest: _lastTest, modelSource: _modelSource, modelsFetchedAt: _modelsFetchedAt, ...retained } = previous;
324
- const migratedEnabledModelIds = isLegacySeed
325
- ? [...input.enabledModelIds]
326
- : previous.enabledModelIds.filter((id) => !retired.has(id));
327
- const connections = [...current.connections];
328
- const modelOverrides = pruneModelOverrides(previous.modelOverrides, Object.keys(previous.modelOverrides ?? {}).filter((id) => !retired.has(id)));
329
- connections[index] = {
330
- ...retained,
331
- revision: nextRevision(previous.revision),
332
- enabledModelIds: migratedEnabledModelIds,
333
- models,
334
- ...(isLegacySeed || previous.modelSource === undefined
335
- ? {}
336
- : { modelSource: previous.modelSource, modelsFetchedAt: previous.modelsFetchedAt }),
337
- ...(modelOverrides === undefined ? {} : { modelOverrides }),
338
- };
339
- const target = current.defaultTarget;
340
- const defaultTarget = target !== null &&
341
- target.connectionId === previous.connectionId &&
342
- !migratedEnabledModelIds.includes(target.modelId)
343
- ? { connectionId: previous.connectionId, modelId: input.defaultModelId }
344
- : target;
345
- const next = this.nextDocument(current, connections, defaultTarget);
346
- await this.write(root, next);
347
- return committed(next);
348
- }
349
287
  async setDefaultTarget(root, rawInput) {
350
288
  const input = decodeConnectionInput(() => normalizeSetDefaultConnectionTargetInput(rawInput));
351
289
  const current = await this.read(root);
@@ -195,9 +195,6 @@ export class RuntimePolicyCoordinator {
195
195
  setDefaultTarget(input) {
196
196
  return this.inLane(async (root) => this.projectCatalogMutation(root, await this.catalog.setDefaultTarget(root, input)));
197
197
  }
198
- migrateSystemSeed(input) {
199
- return this.inLane((root) => this.catalog.migrateSystemSeed(root, input));
200
- }
201
198
  setCredential(rawInput) {
202
199
  return this.setCredentialWithAuthority(rawInput, 'client');
203
200
  }
@@ -1114,6 +1111,29 @@ export class RuntimePolicyCoordinator {
1114
1111
  });
1115
1112
  }));
1116
1113
  }
1114
+ beginConnectionUsage(connectionId) {
1115
+ return this.inLane(async (root) => {
1116
+ const prepared = await this.prepareConnectionOperation(root, connectionId, 'read_usage');
1117
+ if (prepared.kind !== 'ready')
1118
+ return prepared;
1119
+ const ticket = this.issueTicket('connection_usage', connectionUsageSemanticBasis(prepared));
1120
+ return deepFreeze({
1121
+ kind: 'ready',
1122
+ ticket: ticket,
1123
+ connection: structuredClone(prepared.connection),
1124
+ secretMaterial: prepared.secretMaterial,
1125
+ networkProxy: structuredClone(prepared.networkProxy),
1126
+ });
1127
+ });
1128
+ }
1129
+ /**
1130
+ * Read-only counterpart of `completeConnectionTest`: nothing was written, so
1131
+ * there is no catalog state to revalidate — the ticket is simply spent.
1132
+ */
1133
+ async completeConnectionUsage(ticket) {
1134
+ const claimed = this.claimTicket(ticket, 'connection_usage');
1135
+ await this.completeClaimedTicket(claimed, async () => undefined);
1136
+ }
1117
1137
  async prepareConnectionOperation(root, connectionId, action) {
1118
1138
  const catalog = await this.catalog.read(root);
1119
1139
  const connection = findConnection(catalog, { connectionId });
@@ -1574,6 +1594,9 @@ function connectionTestSemanticBasis(prepared) {
1574
1594
  model: connectionTestModelBasis(prepared.connection),
1575
1595
  };
1576
1596
  }
1597
+ function connectionUsageSemanticBasis(prepared) {
1598
+ return { kind: 'connection_usage', ...commonSemanticConnectionBasis(prepared) };
1599
+ }
1577
1600
  function isCanonicalConnectionTestModel(connection, modelId) {
1578
1601
  const basis = connectionTestModelBasis(connection);
1579
1602
  // Either source admits: testing a discovered model before enabling it is the
@@ -1681,7 +1704,14 @@ function assertConnectionIsWritable(connection) {
1681
1704
  }
1682
1705
  }
1683
1706
  function ticketLabel(kind) {
1684
- return kind === 'model_fetch' ? 'model fetch' : 'connection test';
1707
+ switch (kind) {
1708
+ case 'model_fetch':
1709
+ return 'model fetch';
1710
+ case 'connection_test':
1711
+ return 'connection test';
1712
+ case 'connection_usage':
1713
+ return 'connection usage';
1714
+ }
1685
1715
  }
1686
1716
  function networkProxyCredentialLocator() {
1687
1717
  return { scope: 'network_proxy', kind: 'password' };
@@ -97,7 +97,6 @@ function createWriterFacade(coordinator) {
97
97
  update: (input) => coordinator.updateConnection(input),
98
98
  remove: (input) => coordinator.removeConnection(input),
99
99
  setDefaultTarget: (input) => coordinator.setDefaultTarget(input),
100
- migrateSystemSeed: (input) => coordinator.migrateSystemSeed(input),
101
100
  },
102
101
  credentialVault: {
103
102
  getSnapshot: () => coordinator.getVaultSnapshot(),
@@ -127,6 +126,8 @@ function createWriterFacade(coordinator) {
127
126
  completeConnectionOnboarding: (ticket, input) => coordinator.completeConnectionOnboarding(ticket, input),
128
127
  beginConnectionTest: (connectionId, modelId) => coordinator.beginConnectionTest(connectionId, modelId),
129
128
  completeConnectionTest: (ticket, result) => coordinator.completeConnectionTest(ticket, result),
129
+ beginConnectionUsage: (connectionId) => coordinator.beginConnectionUsage(connectionId),
130
+ completeConnectionUsage: (ticket) => coordinator.completeConnectionUsage(ticket),
130
131
  },
131
132
  };
132
133
  freezeFacade(stores);
@@ -68,8 +68,9 @@ class SqliteSessionStore {
68
68
  externalOrigin,
69
69
  transcriptLedgerVersion: 0,
70
70
  };
71
+ const catalogProjection = projectSessionCatalogMessages(canonicalMessages);
71
72
  options.onCommitStarted?.();
72
- const outcome = await this.metadata.importSession(header, canonicalMessages, projectSessionCatalogMessages(canonicalMessages));
73
+ const outcome = await this.metadata.importSession(header, canonicalMessages, catalogProjection);
73
74
  if (outcome !== 'imported') {
74
75
  throw new Error(`Generated Session id already exists: ${header.id}`);
75
76
  }
@@ -285,6 +286,7 @@ class SqliteSessionStore {
285
286
  async list(filter) {
286
287
  await this.ensureReady();
287
288
  return (await this.metadata.list(filter, 'ordinary'))
289
+ .filter((record) => record.header.transcriptLedgerVersion !== 0)
288
290
  .filter((record) => record.header.conversationCopy?.state !== 'preparing')
289
291
  .map((record) => toCatalogSummary(record.header, record.lastMessagePreview));
290
292
  }
@@ -393,7 +395,8 @@ class SqliteSessionStore {
393
395
  if (messages.length === 0)
394
396
  return;
395
397
  await this.ensureReady();
396
- await this.metadata.appendMessages(sessionId, messages, projectSessionCatalogMessages(messages));
398
+ const canonicalMessages = messages.map((message) => decodeCanonicalMessage(JSON.parse(JSON.stringify(message))));
399
+ await this.metadata.appendMessages(sessionId, canonicalMessages, projectSessionCatalogMessages(canonicalMessages));
397
400
  for (const listener of this.transcriptChangeListeners)
398
401
  listener(sessionId);
399
402
  }