maka-agent 0.2.0-dev.53.20260927 → 0.2.0-dev.62.20260928

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 (55) hide show
  1. package/LICENSE +6 -5
  2. package/dist/workspace-root.js +2 -2
  3. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  4. package/node_modules/@maka/acp-executor-plugin/dist/index.js +333 -28
  5. package/node_modules/@maka/acp-executor-plugin/dist/plugin.mjs +283 -27
  6. package/node_modules/@maka/core/dist/executor-catalog.js +10 -1
  7. package/node_modules/@maka/core/dist/message-queue-order.js +47 -0
  8. package/node_modules/@maka/core/dist/model-metadata.js +2 -1
  9. package/node_modules/@maka/core/dist/redaction.js +42 -3
  10. package/node_modules/@maka/core/dist/relative-time-policy.js +71 -0
  11. package/node_modules/@maka/core/dist/relative-time.js +3 -54
  12. package/node_modules/@maka/core/package.json +1 -0
  13. package/node_modules/@maka/eval/dist/egress-audit.js +127 -0
  14. package/node_modules/@maka/eval/dist/harness-executor.js +16 -96
  15. package/node_modules/@maka/eval/harbor/egress-proxy/entrypoint.sh +4 -4
  16. package/node_modules/@maka/eval/harbor/egress_filter.py +153 -104
  17. package/node_modules/@maka/eval/harbor/eval_framework.py +37 -14
  18. package/node_modules/@maka/eval/harbor/relay_agent.py +4 -6
  19. package/node_modules/@maka/eval/harbor/run_trial.py +11 -4
  20. package/node_modules/@maka/runtime/dist/agent-graph-supervisor-wake.js +33 -6
  21. package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +1 -1
  22. package/node_modules/@maka/runtime/dist/plugin-executor-backend.js +26 -5
  23. package/node_modules/@maka/runtime/dist/plugin-executor-service.js +36 -0
  24. package/node_modules/@maka/runtime/dist/provider-error-classification.js +8 -73
  25. package/node_modules/@maka/runtime/dist/provider-error-signals.js +31 -0
  26. package/node_modules/@maka/runtime/dist/provider-retry-policy.js +79 -0
  27. package/node_modules/@maka/runtime/dist/session-manager.js +6 -4
  28. package/node_modules/@maka/runtime/dist/session-projection-helpers.js +2 -0
  29. package/node_modules/@maka/runtime/dist/shell-run-manager.js +8 -8
  30. package/node_modules/@maka/runtime/dist/terminal-run-commit.js +7 -1
  31. package/node_modules/@maka/runtime/dist/tool-runtime.js +5 -4
  32. package/node_modules/@maka/runtime-host/dist/adapter/provider-retry-projector.js +63 -0
  33. package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +7 -51
  34. package/node_modules/@maka/runtime-host/dist/protocol/index.js +9 -3
  35. package/node_modules/@maka/runtime-host/dist/protocol/message-queue-limits.js +21 -0
  36. package/node_modules/@maka/runtime-host/dist/protocol/message.js +6 -104
  37. package/node_modules/@maka/runtime-host/dist/protocol/queue-mutation.js +136 -0
  38. package/node_modules/@maka/runtime-host/dist/protocol/turn-provider-retry.js +69 -0
  39. package/node_modules/@maka/runtime-host/dist/protocol/turn.js +2 -43
  40. package/node_modules/@maka/runtime-host/dist/server/goal-coordinator.js +42 -5
  41. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +105 -233
  42. package/node_modules/@maka/runtime-host/dist/server/message-queue-state.js +69 -0
  43. package/node_modules/@maka/runtime-host/dist/server/provider-retry-projection.js +71 -0
  44. package/node_modules/@maka/runtime-host/dist/server/queued-mutation-executor.js +94 -0
  45. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +1 -1
  46. package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +9 -58
  47. package/node_modules/@maka/storage/dist/agent-run-store-contract.js +0 -3
  48. package/node_modules/@maka/storage/dist/agent-run-store.js +15 -6
  49. package/node_modules/@maka/storage/dist/execution-persistence-provider.js +1 -0
  50. package/node_modules/@maka/storage/dist/execution-stores.js +1 -0
  51. package/node_modules/@maka/storage/dist/project-catalog.js +41 -42
  52. package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +102 -31
  53. package/node_modules/@maka/storage/dist/sqlite-session-metadata-schema.js +52 -1
  54. package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +34 -2
  55. package/package.json +1 -1
@@ -25,6 +25,8 @@ import { MESSAGE_QUEUE_MAX_ENTRIES, MESSAGE_QUEUE_PROJECTION_MAX_BYTES, MESSAGE_
25
25
  import { worstCaseFailedTurnSnapshot } from './canonical-turn-snapshot.js';
26
26
  import { worstCaseMessageQueueProjection } from './message-queue-capacity.js';
27
27
  import { capabilityInitiatingConnectionId, } from './operation-dispatcher.js';
28
+ import { QueuedMutationExecutor, } from './queued-mutation-executor.js';
29
+ import { commitFollowupPromotion, commitQueueReorder, checkQueueRevision, locateQueuedEntry, planQueueReorder, removeQueuedEntry, selectQueuedEntry, } from './message-queue-state.js';
28
30
  const EMPTY_SKILL_INVOCATION = {
29
31
  loaded: [],
30
32
  failed: [],
@@ -45,11 +47,11 @@ export class HostMessageCoordinator {
45
47
  'turn.message.query': (input) => this.queryMessages(input),
46
48
  'turn.message.execution.query': (input) => this.queryMessageExecutions(input),
47
49
  'turn.message.submit': (input, context) => this.submit(input, context),
48
- 'queue.retract': (input) => this.retract(input),
49
- 'queue.entry.retract': (input) => this.retractQueuedEntry(input),
50
- 'queue.entry.promote': (input) => this.promoteQueuedEntry(input),
51
- 'queue.entry.update': (input) => this.updateQueuedEntry(input),
52
- 'queue.entries.reorder': (input) => this.reorderQueuedEntries(input),
50
+ 'queue.retract': this.#queueMutationHandler('queue.retract', 'retract', 'Retract', (input) => input.retractId, (input) => this.#retractAdmitted(input)),
51
+ 'queue.entry.retract': this.#queueMutationHandler('queue.entry.retract', 'retract_entry', 'Retract entry', (input) => input.retractId, (input) => this.#retractQueuedEntryAdmitted(input)),
52
+ 'queue.entry.promote': this.#queueMutationHandler('queue.entry.promote', 'promote', 'Promote entry', (input) => input.promoteId, (input) => this.#promoteQueuedEntryAdmitted(input)),
53
+ 'queue.entry.update': this.#queueMutationHandler('queue.entry.update', 'update_entry', 'Update entry', (input) => input.updateId, (input) => this.#updateQueuedEntryAdmitted(input)),
54
+ 'queue.entries.reorder': this.#queueMutationHandler('queue.entries.reorder', 'reorder', 'Reorder entries', (input) => input.reorderId, (input) => this.#reorderQueuedEntriesAdmitted(input)),
53
55
  'turn.interrupt': (input) => this.interrupt(input),
54
56
  };
55
57
  #hostEpoch;
@@ -64,8 +66,8 @@ export class HostMessageCoordinator {
64
66
  #preflightSessionSnapshot;
65
67
  #sessions = new Map();
66
68
  #pendingSubmits = new Map();
67
- #pendingQueuedMutations = new Map();
68
69
  #completedOperations = new Map();
70
+ #queueMutations;
69
71
  #draining = false;
70
72
  #failStopped = false;
71
73
  constructor(options) {
@@ -82,6 +84,12 @@ export class HostMessageCoordinator {
82
84
  this.#onProjectionChanged = options.onProjectionChanged ?? (() => undefined);
83
85
  this.#createId = options.createId ?? randomUUID;
84
86
  this.#preflightSessionSnapshot = options.preflightSessionSnapshot;
87
+ this.#queueMutations = new QueuedMutationExecutor({
88
+ hostEpoch: this.#hostEpoch,
89
+ admissions: this.#sessionAdmission,
90
+ isFailStopped: () => this.#failStopped,
91
+ readCompleted: (kind, sessionId, operationId) => this.#completedOperations.get(queuedMutationKey(kind, sessionId, operationId)),
92
+ });
85
93
  }
86
94
  projection(sessionId) {
87
95
  const state = this.#sessions.get(sessionId);
@@ -978,26 +986,27 @@ export class HostMessageCoordinator {
978
986
  ? this.#sessionAdmission.runAdmitted(input.sessionId, admittedLease, () => execute(admittedLease))
979
987
  : this.#sessionAdmission.run(input.sessionId, execute);
980
988
  }
981
- retract(input) {
982
- return this.#runQueuedMutation({
983
- spec: MESSAGE_OPERATION_SPECS['queue.retract'],
984
- operationKind: 'retract',
985
- operationId: input.retractId,
986
- verb: 'Retract',
989
+ #runQueueMutation(request) {
990
+ return this.#queueMutations.run({
991
+ ...request,
992
+ payloadIdentity: completedPayloadIdentity(request.kind, request.input),
993
+ });
994
+ }
995
+ #queueMutationHandler(operation, kind, verb, operationId, execute) {
996
+ return (input) => this.#runQueueMutation({
997
+ spec: MESSAGE_OPERATION_SPECS[operation],
998
+ kind,
999
+ id: operationId(input),
1000
+ verb,
987
1001
  input,
988
- execute: () => this.#retractAdmitted(input),
1002
+ execute: () => execute(input),
989
1003
  });
990
1004
  }
991
1005
  async #retractAdmitted(input) {
992
- const header = await this.#root.readSessionHeader(input.sessionId);
993
- if (this.#failStopped) {
994
- return failure('host_draining', 'Runtime Host message authority has failed');
995
- }
996
- if (!header)
997
- return failure('not_found', 'Session does not exist');
998
- if (header.isArchived)
999
- return failure('session_archived', 'Session is archived');
1000
- const state = this.#state(input.sessionId);
1006
+ const admitted = await this.#openQueueMutation(input.sessionId, true);
1007
+ if (!admitted.ok)
1008
+ return admitted;
1009
+ const state = admitted.result;
1001
1010
  if (!retractionResultFits(state, state.revision + (queuedEntryCount(state) > 0 ? 1 : 0), MESSAGE_OPERATION_RESULT_MAX_BYTES)) {
1002
1011
  return failure('session_busy', 'Retract result exceeds protocol capacity');
1003
1012
  }
@@ -1017,140 +1026,27 @@ export class HostMessageCoordinator {
1017
1026
  this.#rememberCompletedOperation('retract', input.sessionId, input.retractId, input, result);
1018
1027
  return success(result);
1019
1028
  }
1020
- retractQueuedEntry(input) {
1021
- return this.#runQueuedMutation({
1022
- spec: MESSAGE_OPERATION_SPECS['queue.entry.retract'],
1023
- operationKind: 'retract_entry',
1024
- operationId: input.retractId,
1025
- verb: 'Retract',
1026
- input,
1027
- execute: () => this.#retractQueuedEntryAdmitted(input),
1028
- });
1029
- }
1030
- promoteQueuedEntry(input) {
1031
- return this.#runQueuedMutation({
1032
- spec: MESSAGE_OPERATION_SPECS['queue.entry.promote'],
1033
- operationKind: 'promote',
1034
- operationId: input.promoteId,
1035
- verb: 'Promote',
1036
- input,
1037
- execute: () => this.#promoteQueuedEntryAdmitted(input),
1038
- });
1039
- }
1040
- updateQueuedEntry(input) {
1041
- return this.#runQueuedMutation({
1042
- spec: MESSAGE_OPERATION_SPECS['queue.entry.update'],
1043
- operationKind: 'update_entry',
1044
- operationId: input.updateId,
1045
- verb: 'Update',
1046
- input,
1047
- execute: () => this.#updateQueuedEntryAdmitted(input),
1048
- });
1049
- }
1050
- reorderQueuedEntries(input) {
1051
- return this.#runQueuedMutation({
1052
- spec: MESSAGE_OPERATION_SPECS['queue.entries.reorder'],
1053
- operationKind: 'reorder',
1054
- operationId: input.reorderId,
1055
- verb: 'Reorder',
1056
- input,
1057
- execute: () => this.#reorderQueuedEntriesAdmitted(input),
1058
- });
1059
- }
1060
- #runQueuedMutation(options) {
1061
- const { input } = options;
1062
- const isCurrentEpoch = input.originHostEpoch === this.#hostEpoch;
1063
- const key = queuedMutationKey(options.operationKind, input.sessionId, options.operationId);
1064
- if (isCurrentEpoch) {
1065
- const pending = this.#pendingQueuedMutations.get(key);
1066
- if (pending) {
1067
- return samePayload(pending.payload, input)
1068
- ? pending.result
1069
- : Promise.resolve(failure('operation_conflict', `${options.verb} identity has a different payload`));
1070
- }
1071
- }
1072
- if (this.#failStopped) {
1073
- return Promise.resolve(failure('host_draining', 'Runtime Host message authority has failed'));
1074
- }
1075
- if (!isCurrentEpoch) {
1076
- return Promise.resolve(failure('outcome_unknown', `${options.verb} outcome is not durable across Host Epochs`));
1077
- }
1078
- const result = this.#admitQueuedMutation(options);
1079
- this.#pendingQueuedMutations.set(key, { payload: input, result });
1080
- void result.then(() => this.#deletePendingQueuedMutation(key, result), () => this.#deletePendingQueuedMutation(key, result));
1081
- return result;
1082
- }
1083
- #admitQueuedMutation(options) {
1084
- return this.#sessionAdmission.run(options.input.sessionId, async () => {
1085
- if (this.#failStopped) {
1086
- return failure('host_draining', 'Runtime Host message authority has failed');
1087
- }
1088
- const receipt = await this.#readCompletedQueuedMutation(options);
1089
- if (receipt) {
1090
- return samePayload(receipt.payloadIdentity, completedPayloadIdentity(options.operationKind, options.input))
1091
- ? success(receipt.result)
1092
- : failure('operation_conflict', `${options.verb} identity has a different payload`);
1093
- }
1094
- return options.execute();
1095
- });
1096
- }
1097
- async #readCompletedQueuedMutation(options) {
1098
- const receipt = this.#completedOperations.get(queuedMutationKey(options.operationKind, options.input.sessionId, options.operationId));
1099
- if (!receipt)
1100
- return undefined;
1101
- try {
1102
- return {
1103
- payloadIdentity: receipt.payloadIdentity,
1104
- result: options.spec.decodeOutput(receipt.result),
1105
- };
1106
- }
1107
- catch (error) {
1108
- throw new RuntimeMessageAuthorityInvariantError(`Invalid queued mutation replay outcome: ${error instanceof Error ? error.message : 'malformed'}`);
1109
- }
1110
- }
1111
- #deletePendingQueuedMutation(key, result) {
1112
- if (this.#pendingQueuedMutations.get(key)?.result === result) {
1113
- this.#pendingQueuedMutations.delete(key);
1114
- }
1115
- }
1116
1029
  async #retractQueuedEntryAdmitted(input) {
1117
- const header = await this.#root.readSessionHeader(input.sessionId);
1118
- if (this.#failStopped) {
1119
- return failure('host_draining', 'Runtime Host message authority has failed');
1120
- }
1121
- if (!header)
1122
- return failure('not_found', 'Session does not exist');
1123
- if (header.isArchived)
1124
- return failure('session_archived', 'Session is archived');
1125
- const state = this.#state(input.sessionId);
1126
- if (state.transition) {
1127
- return failure('operation_conflict', 'Message queue is draining into the next Turn');
1128
- }
1129
- const queued = findQueuedEntry(state, input.entryId);
1130
- if (!queued) {
1131
- if ([...state.inFlight.values()].some((entry) => entry.entryId === input.entryId)) {
1132
- return failure('operation_conflict', 'Message entry is already being delivered');
1133
- }
1134
- return failure('not_found', 'Message queue entry does not exist');
1135
- }
1136
- await this.#admissions.cancelMessageAdmissions(input.sessionId, [queued.entry.messageId]);
1137
- queued.remove();
1138
- this.#releaseEntry(queued.entry);
1030
+ const admitted = await this.#openQueueMutation(input.sessionId);
1031
+ if (!admitted.ok)
1032
+ return admitted;
1033
+ const state = admitted.result;
1034
+ const selected = selectQueuedEntry(state, input.entryId);
1035
+ if (selected.kind !== 'found')
1036
+ return queueEntrySelectionFailure(selected);
1037
+ await this.#admissions.cancelMessageAdmissions(input.sessionId, [
1038
+ selected.location.entry.messageId,
1039
+ ]);
1040
+ this.#releaseEntry(removeQueuedEntry(state, selected.location));
1139
1041
  this.#mutated(state);
1140
1042
  this.#maybeReclaim(input.sessionId, state);
1141
- const result = { queueRevision: state.revision };
1142
- this.#rememberCompletedOperation('retract_entry', input.sessionId, input.retractId, input, result);
1143
- return success(result);
1043
+ return this.#completeQueueEntryMutation('retract_entry', state, input.retractId, input);
1144
1044
  }
1145
1045
  async #promoteQueuedEntryAdmitted(input) {
1146
- const header = await this.#root.readSessionHeader(input.sessionId);
1147
- if (this.#failStopped) {
1148
- return failure('host_draining', 'Runtime Host message authority has failed');
1149
- }
1150
- if (!header)
1151
- return failure('not_found', 'Session does not exist');
1152
- if (header.isArchived)
1153
- return failure('session_archived', 'Session is archived');
1046
+ const admitted = await this.#openQueueMutation(input.sessionId);
1047
+ if (!admitted.ok)
1048
+ return admitted;
1049
+ const state = admitted.result;
1154
1050
  const rootState = await this.#root.readRootState(input.sessionId);
1155
1051
  if (this.#failStopped) {
1156
1052
  return failure('host_draining', 'Runtime Host message authority has failed');
@@ -1158,27 +1054,17 @@ export class HostMessageCoordinator {
1158
1054
  if (rootState.kind !== 'active') {
1159
1055
  return failure('operation_conflict', 'No active Turn can accept steering');
1160
1056
  }
1161
- const state = this.#state(input.sessionId);
1162
1057
  if (state.phase !== 'open') {
1163
1058
  return failure('session_busy', 'Message admission is closed for the active generation');
1164
1059
  }
1165
- if (state.transition) {
1166
- return failure('operation_conflict', 'Message queue is draining into the next Turn');
1167
- }
1168
1060
  if (!state.reservedRoot || !sameRun(state.reservedRoot, rootState)) {
1169
1061
  throw new RuntimeMessageAuthorityInvariantError('Root state does not match message reservation');
1170
1062
  }
1171
- const index = state.followup.findIndex((entry) => entry.entryId === input.entryId);
1172
- const entry = index === -1 ? undefined : state.followup[index];
1173
- if (!entry) {
1174
- if (state.steering.some((queued) => queued.entryId === input.entryId)) {
1175
- return failure('operation_conflict', 'Message entry already steers the active Turn');
1176
- }
1177
- if ([...state.inFlight.values()].some((queued) => queued.entryId === input.entryId)) {
1178
- return failure('operation_conflict', 'Message entry is already being delivered');
1179
- }
1180
- return failure('not_found', 'Message queue entry does not exist');
1063
+ const selected = selectQueuedEntry(state, input.entryId, 'followup');
1064
+ if (selected.kind !== 'found') {
1065
+ return queueEntrySelectionFailure(selected, 'Message entry already steers the active Turn');
1181
1066
  }
1067
+ const entry = selected.location.entry;
1182
1068
  const promotedSource = {
1183
1069
  ...sourceFromEntry(entry),
1184
1070
  placement: 'current_turn',
@@ -1205,34 +1091,24 @@ export class HostMessageCoordinator {
1205
1091
  skillInvocation: entry.skillInvocation,
1206
1092
  admittedAt: entry.admittedAt,
1207
1093
  });
1208
- state.followup.splice(index, 1);
1209
- state.steering.push({ ...entry, placement: 'current_turn', disposition: 'steering' });
1094
+ commitFollowupPromotion(state, selected.location, {
1095
+ ...entry,
1096
+ placement: 'current_turn',
1097
+ disposition: 'steering',
1098
+ });
1210
1099
  this.#mutated(state);
1211
- const result = { queueRevision: state.revision };
1212
- this.#rememberCompletedOperation('promote', input.sessionId, input.promoteId, input, result);
1213
- return success(result);
1100
+ return this.#completeQueueEntryMutation('promote', state, input.promoteId, input);
1214
1101
  }
1215
1102
  async #updateQueuedEntryAdmitted(input) {
1216
- const header = await this.#root.readSessionHeader(input.sessionId);
1217
- if (this.#failStopped) {
1218
- return failure('host_draining', 'Runtime Host message authority has failed');
1219
- }
1220
- if (!header)
1221
- return failure('not_found', 'Session does not exist');
1222
- if (header.isArchived)
1223
- return failure('session_archived', 'Session is archived');
1224
- const state = this.#state(input.sessionId);
1225
- if (state.transition) {
1226
- return failure('operation_conflict', 'Message queue is draining into the next Turn');
1227
- }
1228
- const queued = findQueuedEntry(state, input.entryId);
1229
- if (!queued) {
1230
- if ([...state.inFlight.values()].some((entry) => entry.entryId === input.entryId)) {
1231
- return failure('operation_conflict', 'Message entry is already being delivered');
1232
- }
1233
- return failure('not_found', 'Message queue entry does not exist');
1234
- }
1235
- if (state.revision !== input.expectedQueueRevision) {
1103
+ const admitted = await this.#openQueueMutation(input.sessionId);
1104
+ if (!admitted.ok)
1105
+ return admitted;
1106
+ const state = admitted.result;
1107
+ const selected = selectQueuedEntry(state, input.entryId);
1108
+ if (selected.kind !== 'found')
1109
+ return queueEntrySelectionFailure(selected);
1110
+ const queued = selected.location;
1111
+ if (checkQueueRevision(state.revision, input.expectedQueueRevision).kind === 'stale') {
1236
1112
  return failure('operation_conflict', 'Message queue changed since editing began');
1237
1113
  }
1238
1114
  if (!state.reservedRoot) {
@@ -1282,7 +1158,7 @@ export class HostMessageCoordinator {
1282
1158
  return failure('session_busy', 'Session projection capacity is full');
1283
1159
  }
1284
1160
  if (state.revision !== currentRevision ||
1285
- findQueuedEntry(state, input.entryId)?.entry !== queued.entry) {
1161
+ locateQueuedEntry(state, input.entryId)?.entry !== queued.entry) {
1286
1162
  return failure('session_busy', 'Message queue changed during update');
1287
1163
  }
1288
1164
  const admission = await this.#admissions.readMessageAdmission(input.sessionId, queued.entry.messageId);
@@ -1304,12 +1180,34 @@ export class HostMessageCoordinator {
1304
1180
  queued.entry.submittedContentDigest = messageContentDigest(content);
1305
1181
  queued.entry.skillInvocation = prepared.skillInvocation;
1306
1182
  this.#mutated(state);
1183
+ return this.#completeQueueEntryMutation('update_entry', state, input.updateId, input);
1184
+ }
1185
+ async #reorderQueuedEntriesAdmitted(input) {
1186
+ const admitted = await this.#openQueueMutation(input.sessionId);
1187
+ if (!admitted.ok)
1188
+ return admitted;
1189
+ const state = admitted.result;
1190
+ if (checkQueueRevision(state.revision, input.expectedQueueRevision).kind === 'stale') {
1191
+ return failure('operation_conflict', 'Message queue changed since the reorder was issued');
1192
+ }
1193
+ const reorder = planQueueReorder(state, input.entryIds);
1194
+ if (!reorder) {
1195
+ return failure('operation_conflict', 'Message queue changed since the reorder was issued');
1196
+ }
1197
+ if (reorder.changed) {
1198
+ await this.#admissions.reorderMessageAdmissions(input.sessionId, reorder.entries.map((entry) => entry.messageId), reorder.lane);
1199
+ commitQueueReorder(state, reorder.lane, reorder.entries);
1200
+ this.#mutated(state);
1201
+ }
1202
+ return this.#completeQueueEntryMutation('reorder', state, input.reorderId, input);
1203
+ }
1204
+ #completeQueueEntryMutation(kind, state, operationId, input) {
1307
1205
  const result = { queueRevision: state.revision };
1308
- this.#rememberCompletedOperation('update_entry', input.sessionId, input.updateId, input, result);
1206
+ this.#rememberCompletedOperation(kind, state.sessionId, operationId, input, result);
1309
1207
  return success(result);
1310
1208
  }
1311
- async #reorderQueuedEntriesAdmitted(input) {
1312
- const header = await this.#root.readSessionHeader(input.sessionId);
1209
+ async #openQueueMutation(sessionId, allowTransition = false) {
1210
+ const header = await this.#root.readSessionHeader(sessionId);
1313
1211
  if (this.#failStopped) {
1314
1212
  return failure('host_draining', 'Runtime Host message authority has failed');
1315
1213
  }
@@ -1317,36 +1215,11 @@ export class HostMessageCoordinator {
1317
1215
  return failure('not_found', 'Session does not exist');
1318
1216
  if (header.isArchived)
1319
1217
  return failure('session_archived', 'Session is archived');
1320
- const state = this.#state(input.sessionId);
1321
- if (state.transition) {
1218
+ const state = this.#state(sessionId);
1219
+ if (!allowTransition && state.transition) {
1322
1220
  return failure('operation_conflict', 'Message queue is draining into the next Turn');
1323
1221
  }
1324
- const steering = state.steering.some((entry) => entry.entryId === input.entryIds[0]);
1325
- const current = steering ? state.steering : state.followup;
1326
- if (input.entryIds.length !== current.length) {
1327
- return failure('operation_conflict', 'Message queue changed since the reorder was issued');
1328
- }
1329
- const byId = new Map(current.map((entry) => [entry.entryId, entry]));
1330
- const reordered = [];
1331
- for (const entryId of input.entryIds) {
1332
- const entry = byId.get(entryId);
1333
- if (!entry) {
1334
- return failure('operation_conflict', 'Message queue changed since the reorder was issued');
1335
- }
1336
- byId.delete(entryId);
1337
- reordered.push(entry);
1338
- }
1339
- if (reordered.some((entry, index) => current[index] !== entry)) {
1340
- await this.#admissions.reorderMessageAdmissions(input.sessionId, reordered.map((entry) => entry.messageId), steering ? 'steering' : 'followup');
1341
- if (steering)
1342
- state.steering = reordered;
1343
- else
1344
- state.followup = reordered;
1345
- this.#mutated(state);
1346
- }
1347
- const result = { queueRevision: state.revision };
1348
- this.#rememberCompletedOperation('reorder', input.sessionId, input.reorderId, input, result);
1349
- return success(result);
1222
+ return success(state);
1350
1223
  }
1351
1224
  async interrupt(input) {
1352
1225
  if (input.originHostEpoch !== this.#hostEpoch) {
@@ -1595,7 +1468,7 @@ export class HostMessageCoordinator {
1595
1468
  for (;;) {
1596
1469
  const pending = [
1597
1470
  ...[...this.#pendingSubmits.values()].filter(({ payload }) => payload.sessionId === run.sessionId && payload.placement === 'current_turn'),
1598
- ...[...this.#pendingQueuedMutations.values()].filter(({ payload }) => payload.sessionId === run.sessionId),
1471
+ ...this.#queueMutations.pendingResults(run.sessionId).map((result) => ({ result })),
1599
1472
  ];
1600
1473
  if (pending.length === 0)
1601
1474
  break;
@@ -1800,22 +1673,21 @@ function success(result) {
1800
1673
  function failure(code, message) {
1801
1674
  return { ok: false, error: { code, message } };
1802
1675
  }
1676
+ function queueEntrySelectionFailure(selection, wrongLaneMessage = 'Message queue entry is not in the required lane') {
1677
+ if (selection.kind === 'in_flight') {
1678
+ return failure('operation_conflict', 'Message entry is already being delivered');
1679
+ }
1680
+ if (selection.kind === 'wrong_lane') {
1681
+ return failure('operation_conflict', wrongLaneMessage);
1682
+ }
1683
+ return failure('not_found', 'Message queue entry does not exist');
1684
+ }
1803
1685
  function operationKey(sessionId, operationId) {
1804
1686
  return `${sessionId}\0${operationId}`;
1805
1687
  }
1806
1688
  function queuedMutationKey(kind, sessionId, operationId) {
1807
1689
  return `${kind}\0${sessionId}\0${operationId}`;
1808
1690
  }
1809
- function findQueuedEntry(state, entryId) {
1810
- for (const queue of [state.steering, state.followup]) {
1811
- const index = queue.findIndex((entry) => entry.entryId === entryId);
1812
- const entry = index === -1 ? undefined : queue[index];
1813
- if (!entry)
1814
- continue;
1815
- return { entry, remove: () => queue.splice(index, 1) };
1816
- }
1817
- return undefined;
1818
- }
1819
1691
  function relocateInlineReferences(references, text) {
1820
1692
  if (!references)
1821
1693
  return undefined;
@@ -0,0 +1,69 @@
1
+ /*
2
+ * Licensed to the Apache Software Foundation (ASF) under one
3
+ * or more contributor license agreements. See the NOTICE file
4
+ * distributed with this work for additional information
5
+ * regarding copyright ownership. The ASF licenses this file
6
+ * to you under the Apache License, Version 2.0 (the
7
+ * "License"); you may not use this file except in compliance
8
+ * with the License. You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing,
13
+ * software distributed under the License is distributed on an
14
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+ * KIND, either express or implied. See the License for the
16
+ * specific language governing permissions and limitations
17
+ * under the License.
18
+ */
19
+ import { exactQueueReorder } from '@maka/core/message-queue-order';
20
+ /** The Host owns this fence; clients may only propose a mutation against the revision they read. */
21
+ export function checkQueueRevision(actual, expected) {
22
+ return actual === expected
23
+ ? { kind: 'current', revision: actual }
24
+ : { kind: 'stale', expected, actual };
25
+ }
26
+ export function locateQueuedEntry(state, entryId) {
27
+ for (const lane of ['steering', 'followup']) {
28
+ const index = state[lane].findIndex((entry) => entry.entryId === entryId);
29
+ const entry = index < 0 ? undefined : state[lane][index];
30
+ if (entry)
31
+ return { lane, index, entry };
32
+ }
33
+ return undefined;
34
+ }
35
+ export function hasInFlightEntry(state, entryId) {
36
+ return [...state.inFlight.values()].some((entry) => entry.entryId === entryId);
37
+ }
38
+ export function selectQueuedEntry(state, entryId, requiredLane) {
39
+ const location = locateQueuedEntry(state, entryId);
40
+ if (location && (!requiredLane || location.lane === requiredLane)) {
41
+ return { kind: 'found', location };
42
+ }
43
+ if (location)
44
+ return { kind: 'wrong_lane', lane: location.lane };
45
+ return hasInFlightEntry(state, entryId) ? { kind: 'in_flight' } : { kind: 'missing' };
46
+ }
47
+ export function removeQueuedEntry(state, location) {
48
+ const [removed] = state[location.lane].splice(location.index, 1);
49
+ if (removed !== location.entry)
50
+ throw new Error('Queued entry location changed before commit');
51
+ return removed;
52
+ }
53
+ export function commitFollowupPromotion(state, location, promoted) {
54
+ if (location.lane !== 'followup')
55
+ throw new Error('Only follow-up entries can be promoted');
56
+ removeQueuedEntry(state, location);
57
+ state.steering.push(promoted);
58
+ }
59
+ export function planQueueReorder(state, entryIds) {
60
+ for (const lane of ['steering', 'followup']) {
61
+ const reorder = exactQueueReorder(state[lane], entryIds);
62
+ if (reorder)
63
+ return { lane, entries: reorder.entries, changed: reorder.changed };
64
+ }
65
+ return undefined;
66
+ }
67
+ export function commitQueueReorder(state, lane, entries) {
68
+ state[lane] = [...entries];
69
+ }
@@ -0,0 +1,71 @@
1
+ /*
2
+ * Licensed to the Apache Software Foundation (ASF) under one
3
+ * or more contributor license agreements. See the NOTICE file
4
+ * distributed with this work for additional information
5
+ * regarding copyright ownership. The ASF licenses this file
6
+ * to you under the Apache License, Version 2.0 (the
7
+ * "License"); you may not use this file except in compliance
8
+ * with the License. You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing,
13
+ * software distributed under the License is distributed on an
14
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+ * KIND, either express or implied. See the License for the
16
+ * specific language governing permissions and limitations
17
+ * under the License.
18
+ */
19
+ export function recordProviderRetry(canonical, event) {
20
+ const rootTurn = liveRoot(canonical);
21
+ if (!rootTurn)
22
+ return canonical;
23
+ return {
24
+ ...canonical,
25
+ rootTurn: { ...rootTurn, providerRetry: retrySnapshot(event) },
26
+ };
27
+ }
28
+ export function clearProviderRetry(canonical) {
29
+ const rootTurn = liveRoot(canonical);
30
+ if (!rootTurn?.providerRetry)
31
+ return canonical;
32
+ const { providerRetry: _removed, ...withoutRetry } = rootTurn;
33
+ return { ...canonical, rootTurn: withoutRetry };
34
+ }
35
+ export function carryProviderRetry(current, refreshed) {
36
+ const previous = liveRoot(current);
37
+ const next = liveRoot(refreshed);
38
+ if (!previous?.providerRetry ||
39
+ !next ||
40
+ previous.runId !== next.runId ||
41
+ previous.turnId !== next.turnId ||
42
+ next.providerRetry) {
43
+ return refreshed;
44
+ }
45
+ return { ...refreshed, rootTurn: { ...next, providerRetry: previous.providerRetry } };
46
+ }
47
+ function liveRoot(canonical) {
48
+ const root = canonical.rootTurn;
49
+ if (!root ||
50
+ root.status === 'completed' ||
51
+ root.status === 'failed' ||
52
+ root.status === 'cancelled') {
53
+ return undefined;
54
+ }
55
+ return root;
56
+ }
57
+ function retrySnapshot(event) {
58
+ const common = {
59
+ attempt: event.attempt,
60
+ maxAttempts: event.maxAttempts,
61
+ reason: event.reason,
62
+ };
63
+ return event.phase === 'started'
64
+ ? { phase: 'started', ...common }
65
+ : {
66
+ phase: 'scheduled',
67
+ ...common,
68
+ delayMs: event.delayMs,
69
+ ts: event.ts,
70
+ };
71
+ }