@1mcp/agent 0.34.4 → 0.35.0-beta.1

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 (183) hide show
  1. package/build/admin/assets/admin-console-CX5GzncA.css +1 -0
  2. package/build/admin/assets/admin-console-CkZ5lBKg.js +61 -0
  3. package/build/admin/index.html +13 -0
  4. package/build/commands/admin/admin.d.ts +90 -0
  5. package/build/commands/admin/admin.d.ts.map +1 -0
  6. package/build/commands/admin/admin.js +545 -0
  7. package/build/commands/admin/admin.js.map +1 -0
  8. package/build/commands/admin/index.d.ts +3 -0
  9. package/build/commands/admin/index.d.ts.map +1 -0
  10. package/build/commands/admin/index.js +99 -0
  11. package/build/commands/admin/index.js.map +1 -0
  12. package/build/commands/auth/index.d.ts.map +1 -1
  13. package/build/commands/auth/index.js +24 -5
  14. package/build/commands/auth/index.js.map +1 -1
  15. package/build/commands/auth/login.d.ts +1 -0
  16. package/build/commands/auth/login.d.ts.map +1 -1
  17. package/build/commands/auth/login.js +6 -10
  18. package/build/commands/auth/login.js.map +1 -1
  19. package/build/commands/auth/logout.d.ts +3 -0
  20. package/build/commands/auth/logout.d.ts.map +1 -1
  21. package/build/commands/auth/logout.js +19 -32
  22. package/build/commands/auth/logout.js.map +1 -1
  23. package/build/commands/auth/runtimeTargetContext.d.ts +25 -0
  24. package/build/commands/auth/runtimeTargetContext.d.ts.map +1 -0
  25. package/build/commands/auth/runtimeTargetContext.js +69 -0
  26. package/build/commands/auth/runtimeTargetContext.js.map +1 -0
  27. package/build/commands/auth/status.d.ts +1 -0
  28. package/build/commands/auth/status.d.ts.map +1 -1
  29. package/build/commands/auth/status.js +10 -33
  30. package/build/commands/auth/status.js.map +1 -1
  31. package/build/commands/inspect/index.d.ts.map +1 -1
  32. package/build/commands/inspect/index.js +4 -0
  33. package/build/commands/inspect/index.js.map +1 -1
  34. package/build/commands/inspect/inspect.d.ts +1 -0
  35. package/build/commands/inspect/inspect.d.ts.map +1 -1
  36. package/build/commands/inspect/inspect.js +2 -2
  37. package/build/commands/inspect/inspect.js.map +1 -1
  38. package/build/commands/instructions/index.d.ts.map +1 -1
  39. package/build/commands/instructions/index.js +4 -0
  40. package/build/commands/instructions/index.js.map +1 -1
  41. package/build/commands/instructions/instructions.d.ts +1 -0
  42. package/build/commands/instructions/instructions.d.ts.map +1 -1
  43. package/build/commands/instructions/instructions.js.map +1 -1
  44. package/build/commands/instructions/instructionsUtils.js +1 -1
  45. package/build/commands/instructions/instructionsUtils.js.map +1 -1
  46. package/build/commands/mcp/enable.d.ts +89 -2
  47. package/build/commands/mcp/enable.d.ts.map +1 -1
  48. package/build/commands/mcp/enable.js +555 -35
  49. package/build/commands/mcp/enable.js.map +1 -1
  50. package/build/commands/proxy/index.d.ts +1 -0
  51. package/build/commands/proxy/index.d.ts.map +1 -1
  52. package/build/commands/proxy/index.js +4 -0
  53. package/build/commands/proxy/index.js.map +1 -1
  54. package/build/commands/run/index.d.ts.map +1 -1
  55. package/build/commands/run/index.js +4 -0
  56. package/build/commands/run/index.js.map +1 -1
  57. package/build/commands/run/run.d.ts +1 -0
  58. package/build/commands/run/run.d.ts.map +1 -1
  59. package/build/commands/run/run.js +2 -2
  60. package/build/commands/run/run.js.map +1 -1
  61. package/build/commands/serve/serve.d.ts.map +1 -1
  62. package/build/commands/serve/serve.js +4 -0
  63. package/build/commands/serve/serve.js.map +1 -1
  64. package/build/commands/shared/apiClient.d.ts +5 -1
  65. package/build/commands/shared/apiClient.d.ts.map +1 -1
  66. package/build/commands/shared/apiClient.js +17 -9
  67. package/build/commands/shared/apiClient.js.map +1 -1
  68. package/build/commands/shared/clientSurfaceAttachment.d.ts +14 -0
  69. package/build/commands/shared/clientSurfaceAttachment.d.ts.map +1 -1
  70. package/build/commands/shared/clientSurfaceAttachment.js +51 -9
  71. package/build/commands/shared/clientSurfaceAttachment.js.map +1 -1
  72. package/build/commands/shared/commandRunner.d.ts +3 -1
  73. package/build/commands/shared/commandRunner.d.ts.map +1 -1
  74. package/build/commands/shared/commandRunner.js +59 -2
  75. package/build/commands/shared/commandRunner.js.map +1 -1
  76. package/build/commands/shared/serveTargetResolver.d.ts +14 -1
  77. package/build/commands/shared/serveTargetResolver.d.ts.map +1 -1
  78. package/build/commands/shared/serveTargetResolver.js +145 -3
  79. package/build/commands/shared/serveTargetResolver.js.map +1 -1
  80. package/build/commands/target/index.d.ts +3 -0
  81. package/build/commands/target/index.d.ts.map +1 -0
  82. package/build/commands/target/index.js +171 -0
  83. package/build/commands/target/index.js.map +1 -0
  84. package/build/commands/target/target.d.ts +78 -0
  85. package/build/commands/target/target.d.ts.map +1 -0
  86. package/build/commands/target/target.js +471 -0
  87. package/build/commands/target/target.js.map +1 -0
  88. package/build/constants/mcp.d.ts +1 -1
  89. package/build/constants/mcp.d.ts.map +1 -1
  90. package/build/constants/mcp.js +1 -1
  91. package/build/constants/mcp.js.map +1 -1
  92. package/build/core/runtime/runtimeIdentityService.d.ts +30 -0
  93. package/build/core/runtime/runtimeIdentityService.d.ts.map +1 -0
  94. package/build/core/runtime/runtimeIdentityService.js +63 -0
  95. package/build/core/runtime/runtimeIdentityService.js.map +1 -0
  96. package/build/core/server/agentConfig.d.ts +4 -0
  97. package/build/core/server/agentConfig.d.ts.map +1 -1
  98. package/build/core/server/agentConfig.js +3 -0
  99. package/build/core/server/agentConfig.js.map +1 -1
  100. package/build/core/tools/handlers/serverManagementHandler.d.ts +7 -7
  101. package/build/core/tools/internal/adapters/helpers/configTransformers.d.ts +2 -2
  102. package/build/core/tools/internal/schemas/discovery.d.ts +1 -1
  103. package/build/core/tools/internal/schemas/index.d.ts +13 -13
  104. package/build/core/tools/internal/schemas/installation.d.ts +7 -7
  105. package/build/core/tools/internal/schemas/management.d.ts +5 -5
  106. package/build/core/types/transport.d.ts +9 -3
  107. package/build/core/types/transport.d.ts.map +1 -1
  108. package/build/core/types/transport.js +5 -0
  109. package/build/core/types/transport.js.map +1 -1
  110. package/build/domains/admin/adminConfiguredServerService.d.ts +275 -0
  111. package/build/domains/admin/adminConfiguredServerService.d.ts.map +1 -0
  112. package/build/domains/admin/adminConfiguredServerService.js +1926 -0
  113. package/build/domains/admin/adminConfiguredServerService.js.map +1 -0
  114. package/build/domains/admin/adminConnectivityChecker.d.ts +7 -0
  115. package/build/domains/admin/adminConnectivityChecker.d.ts.map +1 -0
  116. package/build/domains/admin/adminConnectivityChecker.js +42 -0
  117. package/build/domains/admin/adminConnectivityChecker.js.map +1 -0
  118. package/build/domains/admin/adminDomain.d.ts +29 -0
  119. package/build/domains/admin/adminDomain.d.ts.map +1 -0
  120. package/build/domains/admin/adminDomain.js +39 -0
  121. package/build/domains/admin/adminDomain.js.map +1 -0
  122. package/build/domains/admin/adminIdentityService.d.ts +75 -0
  123. package/build/domains/admin/adminIdentityService.d.ts.map +1 -0
  124. package/build/domains/admin/adminIdentityService.js +321 -0
  125. package/build/domains/admin/adminIdentityService.js.map +1 -0
  126. package/build/domains/admin/adminOperationService.d.ts +202 -0
  127. package/build/domains/admin/adminOperationService.d.ts.map +1 -0
  128. package/build/domains/admin/adminOperationService.js +724 -0
  129. package/build/domains/admin/adminOperationService.js.map +1 -0
  130. package/build/domains/admin/adminPresetService.d.ts +140 -0
  131. package/build/domains/admin/adminPresetService.d.ts.map +1 -0
  132. package/build/domains/admin/adminPresetService.js +248 -0
  133. package/build/domains/admin/adminPresetService.js.map +1 -0
  134. package/build/domains/admin/runtimeScopeAdminLock.d.ts +22 -0
  135. package/build/domains/admin/runtimeScopeAdminLock.d.ts.map +1 -0
  136. package/build/domains/admin/runtimeScopeAdminLock.js +121 -0
  137. package/build/domains/admin/runtimeScopeAdminLock.js.map +1 -0
  138. package/build/domains/config-change/configChange.d.ts +6 -1
  139. package/build/domains/config-change/configChange.d.ts.map +1 -1
  140. package/build/domains/config-change/configChange.js +344 -0
  141. package/build/domains/config-change/configChange.js.map +1 -1
  142. package/build/domains/config-change/types.d.ts +18 -3
  143. package/build/domains/config-change/types.d.ts.map +1 -1
  144. package/build/domains/preset/manager/presetManager.d.ts +1 -0
  145. package/build/domains/preset/manager/presetManager.d.ts.map +1 -1
  146. package/build/domains/preset/manager/presetManager.js +3 -0
  147. package/build/domains/preset/manager/presetManager.js.map +1 -1
  148. package/build/domains/preset/tagAuthoring.d.ts +10 -0
  149. package/build/domains/preset/tagAuthoring.d.ts.map +1 -0
  150. package/build/domains/preset/tagAuthoring.js +94 -0
  151. package/build/domains/preset/tagAuthoring.js.map +1 -0
  152. package/build/domains/runtime-targets/runtimeIdentityVerification.d.ts +51 -0
  153. package/build/domains/runtime-targets/runtimeIdentityVerification.d.ts.map +1 -0
  154. package/build/domains/runtime-targets/runtimeIdentityVerification.js +258 -0
  155. package/build/domains/runtime-targets/runtimeIdentityVerification.js.map +1 -0
  156. package/build/domains/runtime-targets/runtimeTargetStore.d.ts +222 -0
  157. package/build/domains/runtime-targets/runtimeTargetStore.d.ts.map +1 -0
  158. package/build/domains/runtime-targets/runtimeTargetStore.js +1456 -0
  159. package/build/domains/runtime-targets/runtimeTargetStore.js.map +1 -0
  160. package/build/index.d.ts.map +1 -1
  161. package/build/index.js +7 -1
  162. package/build/index.js.map +1 -1
  163. package/build/transport/http/routes/adminRoutes.d.ts +34 -0
  164. package/build/transport/http/routes/adminRoutes.d.ts.map +1 -0
  165. package/build/transport/http/routes/adminRoutes.js +1217 -0
  166. package/build/transport/http/routes/adminRoutes.js.map +1 -0
  167. package/build/transport/http/routes/oauthRoutes.d.ts +2 -0
  168. package/build/transport/http/routes/oauthRoutes.d.ts.map +1 -1
  169. package/build/transport/http/routes/oauthRoutes.js +5 -185
  170. package/build/transport/http/routes/oauthRoutes.js.map +1 -1
  171. package/build/transport/http/routes/runtimeIdentityRoutes.d.ts +7 -0
  172. package/build/transport/http/routes/runtimeIdentityRoutes.d.ts.map +1 -0
  173. package/build/transport/http/routes/runtimeIdentityRoutes.js +9 -0
  174. package/build/transport/http/routes/runtimeIdentityRoutes.js.map +1 -0
  175. package/build/transport/http/server.d.ts +3 -0
  176. package/build/transport/http/server.d.ts.map +1 -1
  177. package/build/transport/http/server.js +92 -3
  178. package/build/transport/http/server.js.map +1 -1
  179. package/build/utils/validation/urlDetection.d.ts +13 -2
  180. package/build/utils/validation/urlDetection.d.ts.map +1 -1
  181. package/build/utils/validation/urlDetection.js +37 -6
  182. package/build/utils/validation/urlDetection.js.map +1 -1
  183. package/package.json +22 -9
@@ -0,0 +1,724 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ const ADMIN_STATE_DIR = 'admin';
5
+ const JOURNAL_VERSION = 1;
6
+ const DEFAULT_COMPLETED_RETENTION_MS = 24 * 60 * 60 * 1000;
7
+ const DEFAULT_AUDIT_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
8
+ const DEFAULT_IN_FLIGHT_WAIT_MS = 100;
9
+ const runtimeScopeMutationStates = new Map();
10
+ export class AdminOperationService {
11
+ runtimeScopeId;
12
+ storageDir;
13
+ now;
14
+ completedRetentionMs;
15
+ auditRetentionMs;
16
+ inFlightWaitMs;
17
+ createOperationId;
18
+ mutationAvailability;
19
+ idempotency;
20
+ recentAuditFacts;
21
+ mutationState;
22
+ constructor(options) {
23
+ this.runtimeScopeId = options.runtimeScopeId;
24
+ this.storageDir = path.join(options.storageDir, ADMIN_STATE_DIR);
25
+ this.now = options.now ?? (() => new Date());
26
+ this.completedRetentionMs = options.completedRetentionMs ?? DEFAULT_COMPLETED_RETENTION_MS;
27
+ this.auditRetentionMs = options.auditRetentionMs ?? DEFAULT_AUDIT_RETENTION_MS;
28
+ this.inFlightWaitMs = options.inFlightWaitMs ?? DEFAULT_IN_FLIGHT_WAIT_MS;
29
+ this.createOperationId = options.createOperationId ?? (() => `op_${randomUUID()}`);
30
+ this.mutationAvailability = options.mutationAvailability ?? { available: true };
31
+ this.mutationState = getRuntimeScopeMutationState(this.storageDir, this.runtimeScopeId);
32
+ this.idempotency = this.mutationState.idempotency;
33
+ this.recentAuditFacts = this.mutationState.recentAuditFacts;
34
+ this.replayJournal();
35
+ }
36
+ async executeReadOnly(input) {
37
+ const result = await input.run(input.context);
38
+ return {
39
+ ok: true,
40
+ status: 'completed',
41
+ operationId: this.createOperationId(),
42
+ operationName: input.operationName,
43
+ result,
44
+ replayed: false,
45
+ };
46
+ }
47
+ async executeDryRun(input) {
48
+ const admissionResult = this.validateRuntimeScope(input.context, input.operationName);
49
+ if (admissionResult) {
50
+ return admissionResult;
51
+ }
52
+ try {
53
+ const result = await input.run(input.context);
54
+ return {
55
+ ok: true,
56
+ status: 'completed',
57
+ operationId: this.createOperationId(),
58
+ operationName: input.operationName,
59
+ result,
60
+ replayed: false,
61
+ };
62
+ }
63
+ catch (error) {
64
+ return {
65
+ ok: false,
66
+ status: 'mutation_failed',
67
+ code: 'mutation_failed',
68
+ retryable: false,
69
+ operationName: input.operationName,
70
+ error: error instanceof Error ? error.message : 'Admin dry-run failed',
71
+ };
72
+ }
73
+ }
74
+ getRecentAuditFacts(options = {}) {
75
+ const limit = Math.max(0, options.limit ?? this.recentAuditFacts.length);
76
+ if (limit === 0) {
77
+ return [];
78
+ }
79
+ return this.recentAuditFacts.slice(-limit).map((fact) => ({
80
+ ...fact,
81
+ actor: { ...fact.actor },
82
+ target: { ...fact.target },
83
+ request: { ...fact.request },
84
+ confirmationFacts: fact.confirmationFacts ? { ...fact.confirmationFacts } : undefined,
85
+ }));
86
+ }
87
+ async executeMutation(input) {
88
+ const admissionResult = this.validateMutationAdmission(input.context, input.operationName);
89
+ if (admissionResult) {
90
+ return admissionResult;
91
+ }
92
+ if (this.mutationState.journalUnavailable) {
93
+ return this.journalUnavailableResult(input.operationName);
94
+ }
95
+ const idempotencyKey = input.context.idempotencyKey?.trim();
96
+ const requestFingerprint = input.context.requestFingerprint?.trim();
97
+ if (!idempotencyKey || !requestFingerprint) {
98
+ return {
99
+ ok: false,
100
+ status: 'idempotency_key_required',
101
+ code: 'idempotency_key_required',
102
+ retryable: false,
103
+ operationName: input.operationName,
104
+ };
105
+ }
106
+ const scopedKeyHash = this.scopedKeyHash(input.context, input.operationName, idempotencyKey);
107
+ const fingerprintHash = hashSecret(requestFingerprint);
108
+ let existing = this.idempotency.get(scopedKeyHash);
109
+ if (existing && this.isExpiredTerminal(existing)) {
110
+ this.idempotency.delete(scopedKeyHash);
111
+ existing = undefined;
112
+ }
113
+ if (existing && existing.fingerprintHash !== fingerprintHash) {
114
+ return {
115
+ ok: false,
116
+ status: 'idempotency_conflict',
117
+ code: 'idempotency_conflict',
118
+ retryable: false,
119
+ operationName: input.operationName,
120
+ };
121
+ }
122
+ if (existing?.state === 'completed' && !this.isExpired(existing.completedAt ?? existing.reservedAt)) {
123
+ return {
124
+ ok: true,
125
+ status: 'completed',
126
+ operationId: existing.operationId,
127
+ operationName: input.operationName,
128
+ result: existing.result,
129
+ replayed: true,
130
+ };
131
+ }
132
+ if (existing?.state === 'failed' && !this.isExpired(existing.completedAt ?? existing.reservedAt)) {
133
+ return {
134
+ ok: false,
135
+ status: 'mutation_failed',
136
+ code: 'mutation_failed',
137
+ retryable: false,
138
+ operationName: existing.operationName,
139
+ error: existing.error ?? 'Admin operation failed',
140
+ };
141
+ }
142
+ if (existing?.state === 'state_unknown') {
143
+ return this.stateUnknownResult(existing);
144
+ }
145
+ if (existing?.state === 'in_flight') {
146
+ return (await this.waitForActiveMutation(scopedKeyHash, input.operationName));
147
+ }
148
+ const activePreparation = this.mutationState.activePreparations.get(scopedKeyHash);
149
+ if (activePreparation) {
150
+ if (activePreparation.fingerprintHash !== fingerprintHash) {
151
+ return {
152
+ ok: false,
153
+ status: 'idempotency_conflict',
154
+ code: 'idempotency_conflict',
155
+ retryable: false,
156
+ operationName: input.operationName,
157
+ };
158
+ }
159
+ return (await this.waitForActivePreparation(activePreparation, input.operationName));
160
+ }
161
+ const preparationPromise = this.prepareAndExecuteMutation(input, scopedKeyHash, fingerprintHash);
162
+ this.mutationState.activePreparations.set(scopedKeyHash, {
163
+ fingerprintHash,
164
+ promise: preparationPromise,
165
+ });
166
+ try {
167
+ return await preparationPromise;
168
+ }
169
+ finally {
170
+ const active = this.mutationState.activePreparations.get(scopedKeyHash);
171
+ if (active?.promise === preparationPromise) {
172
+ this.mutationState.activePreparations.delete(scopedKeyHash);
173
+ }
174
+ }
175
+ }
176
+ async prepareAndExecuteMutation(input, scopedKeyHash, fingerprintHash) {
177
+ const prepared = 'prepare' in input ? await input.prepare() : input;
178
+ const readyInput = {
179
+ context: input.context,
180
+ operationName: input.operationName,
181
+ confirmationRequirements: prepared.confirmationRequirements,
182
+ run: prepared.run,
183
+ };
184
+ const confirmationResult = this.validateConfirmations(readyInput);
185
+ if (confirmationResult) {
186
+ return confirmationResult;
187
+ }
188
+ const operationId = this.createOperationId();
189
+ const reservedAt = this.now().toISOString();
190
+ const entry = {
191
+ state: 'in_flight',
192
+ scopedKeyHash,
193
+ fingerprintHash,
194
+ operationId,
195
+ operationName: input.operationName,
196
+ target: sanitizeTarget(input.context.target),
197
+ reservedAt,
198
+ };
199
+ try {
200
+ this.appendJournalRecord(this.reservedRecord(input.context, input.operationName, entry));
201
+ }
202
+ catch {
203
+ this.idempotency.delete(scopedKeyHash);
204
+ this.mutationState.journalUnavailable = true;
205
+ return this.journalUnavailableResult(input.operationName);
206
+ }
207
+ this.idempotency.set(scopedKeyHash, entry);
208
+ const activePromise = this.enqueueMutation(async () => this.runReservedMutation(readyInput, entry));
209
+ this.mutationState.activeMutations.set(scopedKeyHash, {
210
+ promise: activePromise,
211
+ });
212
+ activePromise.finally(() => {
213
+ this.mutationState.activeMutations.delete(scopedKeyHash);
214
+ });
215
+ return (await activePromise);
216
+ }
217
+ async waitForActivePreparation(active, operationName) {
218
+ const timeoutMs = this.retryWaitMs();
219
+ const timeout = new Promise((resolve) => {
220
+ setTimeout(() => resolve(this.operationInProgress(operationName, timeoutMs)), timeoutMs);
221
+ });
222
+ return Promise.race([active.promise, timeout]);
223
+ }
224
+ validateMutationAdmission(context, operationName) {
225
+ const runtimeScopeResult = this.validateRuntimeScope(context, operationName);
226
+ if (runtimeScopeResult)
227
+ return runtimeScopeResult;
228
+ if (!this.mutationAvailability.available) {
229
+ return {
230
+ ok: false,
231
+ status: 'runtime_scope_locked',
232
+ code: 'runtime_scope_locked',
233
+ retryable: true,
234
+ operationName,
235
+ reason: 'writer_lock_unavailable',
236
+ };
237
+ }
238
+ return null;
239
+ }
240
+ validateRuntimeScope(context, operationName) {
241
+ if (context.runtimeIdentity.runtimeScopeId === this.runtimeScopeId)
242
+ return null;
243
+ return {
244
+ ok: false,
245
+ status: 'runtime_scope_mismatch',
246
+ code: 'runtime_scope_mismatch',
247
+ retryable: false,
248
+ operationName,
249
+ };
250
+ }
251
+ async runReservedMutation(input, entry) {
252
+ let result;
253
+ try {
254
+ result = await input.run(input.context);
255
+ }
256
+ catch (error) {
257
+ return this.recordMutationFailure(input, entry, error);
258
+ }
259
+ const completedAt = this.now().toISOString();
260
+ const completedEntry = {
261
+ ...entry,
262
+ state: 'completed',
263
+ completedAt,
264
+ result,
265
+ };
266
+ try {
267
+ this.appendJournalRecord({
268
+ schemaVersion: JOURNAL_VERSION,
269
+ type: 'completed',
270
+ runtimeScopeId: this.runtimeScopeId,
271
+ timestamp: completedAt,
272
+ operationId: entry.operationId,
273
+ operationName: entry.operationName,
274
+ scopedKeyHash: entry.scopedKeyHash,
275
+ fingerprintHash: entry.fingerprintHash,
276
+ result,
277
+ });
278
+ this.appendAuditRecord(input.context, entry, 'completed');
279
+ this.idempotency.set(entry.scopedKeyHash, completedEntry);
280
+ return {
281
+ ok: true,
282
+ status: 'completed',
283
+ operationId: entry.operationId,
284
+ operationName: entry.operationName,
285
+ result,
286
+ replayed: false,
287
+ };
288
+ }
289
+ catch {
290
+ return this.markStateUnknownResult(entry);
291
+ }
292
+ }
293
+ recordMutationFailure(input, entry, error) {
294
+ const failedAt = this.now().toISOString();
295
+ const message = error instanceof Error ? error.message : 'Admin operation failed';
296
+ try {
297
+ this.appendJournalRecord({
298
+ schemaVersion: JOURNAL_VERSION,
299
+ type: 'failed',
300
+ runtimeScopeId: this.runtimeScopeId,
301
+ timestamp: failedAt,
302
+ operationId: entry.operationId,
303
+ operationName: entry.operationName,
304
+ scopedKeyHash: entry.scopedKeyHash,
305
+ fingerprintHash: entry.fingerprintHash,
306
+ error: message,
307
+ });
308
+ this.appendAuditRecord(input.context, entry, 'failed');
309
+ this.idempotency.set(entry.scopedKeyHash, {
310
+ ...entry,
311
+ state: 'failed',
312
+ completedAt: failedAt,
313
+ error: message,
314
+ });
315
+ }
316
+ catch {
317
+ this.mutationState.journalUnavailable = true;
318
+ return this.journalUnavailableResult(entry.operationName);
319
+ }
320
+ return {
321
+ ok: false,
322
+ status: 'mutation_failed',
323
+ code: 'mutation_failed',
324
+ retryable: false,
325
+ operationName: entry.operationName,
326
+ error: message,
327
+ };
328
+ }
329
+ enqueueMutation(operation) {
330
+ const run = this.mutationState.mutationQueue.then(operation, operation);
331
+ this.mutationState.mutationQueue = run.then(() => undefined, () => undefined);
332
+ return run;
333
+ }
334
+ async waitForActiveMutation(scopedKeyHash, operationName) {
335
+ const active = this.mutationState.activeMutations.get(scopedKeyHash);
336
+ if (!active) {
337
+ const entry = this.idempotency.get(scopedKeyHash);
338
+ return entry ? this.markStateUnknownResult(entry) : this.operationInProgress(operationName);
339
+ }
340
+ const timeoutMs = this.retryWaitMs();
341
+ const timeout = new Promise((resolve) => {
342
+ setTimeout(() => resolve(this.operationInProgress(operationName, timeoutMs)), timeoutMs);
343
+ });
344
+ return Promise.race([active.promise, timeout]);
345
+ }
346
+ retryWaitMs() {
347
+ return Math.max(1, this.inFlightWaitMs);
348
+ }
349
+ operationInProgress(operationName, retryAfterMs = this.retryWaitMs()) {
350
+ return {
351
+ ok: false,
352
+ status: 'operation_in_progress',
353
+ code: 'operation_in_progress',
354
+ retryable: true,
355
+ operationName,
356
+ retryAfterMs,
357
+ };
358
+ }
359
+ journalUnavailableResult(operationName) {
360
+ return {
361
+ ok: false,
362
+ status: 'admin_operation_journal_unavailable',
363
+ code: 'admin_operation_journal_unavailable',
364
+ retryable: false,
365
+ operationName,
366
+ };
367
+ }
368
+ validateConfirmations(input) {
369
+ if (!input.confirmationRequirements?.length) {
370
+ return null;
371
+ }
372
+ const facts = input.context.confirmationFacts ?? {};
373
+ const missing = input.confirmationRequirements.filter((requirement) => {
374
+ const actual = facts[requirement.code];
375
+ return requirement.expected === undefined ? actual !== true : actual !== requirement.expected;
376
+ });
377
+ if (missing.length === 0) {
378
+ return null;
379
+ }
380
+ return {
381
+ ok: false,
382
+ status: 'mutation_confirmation_required',
383
+ code: 'mutation_confirmation_required',
384
+ retryable: false,
385
+ operationName: input.operationName,
386
+ confirmationRequirements: input.confirmationRequirements.map((requirement) => ({ ...requirement })),
387
+ };
388
+ }
389
+ replayJournal() {
390
+ const filePath = this.journalFilePath();
391
+ if (!fs.existsSync(filePath)) {
392
+ return;
393
+ }
394
+ try {
395
+ const records = this.readJournalRecords(filePath);
396
+ this.idempotency.clear();
397
+ this.recentAuditFacts.length = 0;
398
+ this.mutationState.journalUnavailable = false;
399
+ for (const record of records) {
400
+ this.applyJournalRecord(record);
401
+ }
402
+ for (const entry of Array.from(this.idempotency.values())) {
403
+ if (entry.state === 'in_flight' && !this.mutationState.activeMutations.has(entry.scopedKeyHash)) {
404
+ this.markStateUnknown(entry);
405
+ }
406
+ }
407
+ }
408
+ catch {
409
+ this.idempotency.clear();
410
+ this.recentAuditFacts.length = 0;
411
+ this.mutationState.journalUnavailable = true;
412
+ return;
413
+ }
414
+ try {
415
+ this.compactJournal();
416
+ }
417
+ catch {
418
+ // Compaction is cleanup only; replayed admission/audit state remains authoritative.
419
+ }
420
+ }
421
+ applyJournalRecord(record) {
422
+ if (record.schemaVersion !== JOURNAL_VERSION || record.runtimeScopeId !== this.runtimeScopeId) {
423
+ return;
424
+ }
425
+ if (record.type === 'reserved') {
426
+ this.idempotency.set(record.scopedKeyHash, {
427
+ state: 'in_flight',
428
+ scopedKeyHash: record.scopedKeyHash,
429
+ fingerprintHash: record.fingerprintHash,
430
+ operationId: record.operationId,
431
+ operationName: record.operationName,
432
+ target: record.target,
433
+ reservedAt: record.timestamp,
434
+ });
435
+ return;
436
+ }
437
+ if (record.type === 'completed') {
438
+ if (this.isExpired(record.timestamp)) {
439
+ this.idempotency.delete(record.scopedKeyHash);
440
+ return;
441
+ }
442
+ this.idempotency.set(record.scopedKeyHash, {
443
+ ...this.entryFromRecord(record),
444
+ state: 'completed',
445
+ completedAt: record.timestamp,
446
+ result: record.result,
447
+ });
448
+ return;
449
+ }
450
+ if (record.type === 'failed') {
451
+ if (this.isExpired(record.timestamp)) {
452
+ this.idempotency.delete(record.scopedKeyHash);
453
+ return;
454
+ }
455
+ this.idempotency.set(record.scopedKeyHash, {
456
+ ...this.entryFromRecord(record),
457
+ state: 'failed',
458
+ completedAt: record.timestamp,
459
+ error: record.error,
460
+ });
461
+ return;
462
+ }
463
+ if (record.type === 'state_unknown') {
464
+ if (this.isAuditExpired(record.timestamp)) {
465
+ this.idempotency.delete(record.scopedKeyHash);
466
+ return;
467
+ }
468
+ this.idempotency.set(record.scopedKeyHash, {
469
+ state: 'state_unknown',
470
+ scopedKeyHash: record.scopedKeyHash,
471
+ fingerprintHash: record.fingerprintHash,
472
+ operationId: record.operationId,
473
+ operationName: record.operationName,
474
+ target: record.target,
475
+ reservedAt: record.reservedAt,
476
+ });
477
+ return;
478
+ }
479
+ if (record.type === 'audit') {
480
+ if (this.isAuditExpired(record.timestamp)) {
481
+ return;
482
+ }
483
+ this.recentAuditFacts.push(auditFactFromRecord(record));
484
+ }
485
+ }
486
+ entryFromRecord(record) {
487
+ const existing = this.idempotency.get(record.scopedKeyHash);
488
+ return {
489
+ scopedKeyHash: record.scopedKeyHash,
490
+ fingerprintHash: record.fingerprintHash,
491
+ operationId: record.operationId,
492
+ operationName: record.operationName,
493
+ target: existing?.target ?? { type: 'unknown' },
494
+ reservedAt: existing?.reservedAt ?? record.timestamp,
495
+ };
496
+ }
497
+ markStateUnknown(entry) {
498
+ const unknownEntry = {
499
+ ...entry,
500
+ state: 'state_unknown',
501
+ };
502
+ this.appendJournalRecord({
503
+ schemaVersion: JOURNAL_VERSION,
504
+ type: 'state_unknown',
505
+ runtimeScopeId: this.runtimeScopeId,
506
+ timestamp: this.now().toISOString(),
507
+ operationId: entry.operationId,
508
+ operationName: entry.operationName,
509
+ scopedKeyHash: entry.scopedKeyHash,
510
+ fingerprintHash: entry.fingerprintHash,
511
+ target: entry.target,
512
+ reservedAt: entry.reservedAt,
513
+ });
514
+ this.idempotency.set(entry.scopedKeyHash, unknownEntry);
515
+ return unknownEntry;
516
+ }
517
+ markStateUnknownResult(entry) {
518
+ try {
519
+ return this.stateUnknownResult(this.markStateUnknown(entry));
520
+ }
521
+ catch {
522
+ this.mutationState.journalUnavailable = true;
523
+ this.idempotency.set(entry.scopedKeyHash, {
524
+ ...entry,
525
+ state: 'state_unknown',
526
+ });
527
+ return this.journalUnavailableResult(entry.operationName);
528
+ }
529
+ }
530
+ stateUnknownResult(entry) {
531
+ return {
532
+ ok: false,
533
+ status: 'operation_state_unknown',
534
+ code: 'operation_state_unknown',
535
+ retryable: false,
536
+ operationName: entry.operationName,
537
+ target: entry.target,
538
+ reservedAt: entry.reservedAt,
539
+ recovery: 'inspect_current_state_and_retry_with_new_idempotency_key',
540
+ };
541
+ }
542
+ reservedRecord(context, operationName, entry) {
543
+ return {
544
+ schemaVersion: JOURNAL_VERSION,
545
+ type: 'reserved',
546
+ runtimeScopeId: this.runtimeScopeId,
547
+ timestamp: entry.reservedAt,
548
+ operationId: entry.operationId,
549
+ operationName,
550
+ scopedKeyHash: entry.scopedKeyHash,
551
+ fingerprintHash: entry.fingerprintHash,
552
+ target: entry.target,
553
+ actor: sanitizeActor(context.actor),
554
+ origin: context.origin,
555
+ request: sanitizeRequest(context.request),
556
+ runtimeIdentity: sanitizeRuntimeIdentity(context.runtimeIdentity),
557
+ };
558
+ }
559
+ appendAuditRecord(context, entry, result) {
560
+ const fact = {
561
+ timestamp: this.now().toISOString(),
562
+ operationId: entry.operationId,
563
+ operationName: entry.operationName,
564
+ result,
565
+ actor: sanitizeActor(context.actor),
566
+ origin: context.origin,
567
+ target: entry.target,
568
+ request: { requestId: context.request.requestId },
569
+ confirmationFacts: sanitizeConfirmationFacts(context.confirmationFacts),
570
+ };
571
+ this.appendJournalRecord({
572
+ schemaVersion: JOURNAL_VERSION,
573
+ type: 'audit',
574
+ runtimeScopeId: this.runtimeScopeId,
575
+ timestamp: fact.timestamp,
576
+ operationId: fact.operationId,
577
+ operationName: fact.operationName,
578
+ scopedKeyHash: entry.scopedKeyHash,
579
+ result: fact.result,
580
+ actor: fact.actor,
581
+ origin: fact.origin,
582
+ target: fact.target,
583
+ request: fact.request,
584
+ confirmationFacts: fact.confirmationFacts,
585
+ });
586
+ this.recentAuditFacts.push(fact);
587
+ }
588
+ appendJournalRecord(record) {
589
+ fs.mkdirSync(this.storageDir, { recursive: true });
590
+ const filePath = this.journalFilePath();
591
+ const fd = fs.openSync(filePath, 'a', 0o600);
592
+ try {
593
+ fs.chmodSync(filePath, 0o600);
594
+ fs.writeSync(fd, `${JSON.stringify(record)}\n`, undefined, 'utf8');
595
+ fs.fsyncSync(fd);
596
+ }
597
+ finally {
598
+ fs.closeSync(fd);
599
+ }
600
+ }
601
+ scopedKeyHash(context, operationName, idempotencyKey) {
602
+ return hashSecret(JSON.stringify({
603
+ runtimeScopeId: this.runtimeScopeId,
604
+ actorType: context.actor.type,
605
+ accountId: context.actor.accountId,
606
+ sessionId: context.actor.sessionId,
607
+ operationName,
608
+ idempotencyKey,
609
+ }));
610
+ }
611
+ isExpired(timestamp) {
612
+ return this.now().getTime() - new Date(timestamp).getTime() > this.completedRetentionMs;
613
+ }
614
+ isAuditExpired(timestamp) {
615
+ return this.now().getTime() - new Date(timestamp).getTime() > this.auditRetentionMs;
616
+ }
617
+ isExpiredTerminal(entry) {
618
+ return ((entry.state === 'completed' || entry.state === 'failed') && this.isExpired(entry.completedAt ?? entry.reservedAt));
619
+ }
620
+ compactJournal() {
621
+ const filePath = this.journalFilePath();
622
+ if (!fs.existsSync(filePath)) {
623
+ return;
624
+ }
625
+ const records = this.readJournalRecords(filePath);
626
+ const retained = records.filter((record) => this.shouldRetainJournalRecord(record));
627
+ if (retained.length === records.length) {
628
+ return;
629
+ }
630
+ const tempPath = `${filePath}.${process.pid}.compact.tmp`;
631
+ const content = retained.length > 0 ? `${retained.map((record) => JSON.stringify(record)).join('\n')}\n` : '';
632
+ fs.writeFileSync(tempPath, content, { encoding: 'utf8', mode: 0o600 });
633
+ fs.renameSync(tempPath, filePath);
634
+ fs.chmodSync(filePath, 0o600);
635
+ }
636
+ shouldRetainJournalRecord(record) {
637
+ if (record.type === 'state_unknown') {
638
+ return !this.isAuditExpired(record.timestamp);
639
+ }
640
+ if (record.type === 'audit') {
641
+ return !this.isAuditExpired(record.timestamp);
642
+ }
643
+ if (record.type === 'completed' || record.type === 'failed') {
644
+ return !this.isExpired(record.timestamp);
645
+ }
646
+ const entry = this.idempotency.get(record.scopedKeyHash);
647
+ return Boolean(entry && !this.isExpiredTerminal(entry));
648
+ }
649
+ readJournalRecords(filePath) {
650
+ return fs
651
+ .readFileSync(filePath, 'utf8')
652
+ .split('\n')
653
+ .filter((line) => line.trim())
654
+ .map((line) => JSON.parse(line));
655
+ }
656
+ journalFilePath() {
657
+ return path.join(this.storageDir, `admin-operations-${hashSecret(this.runtimeScopeId).slice(0, 24)}.jsonl`);
658
+ }
659
+ }
660
+ function sanitizeActor(actor) {
661
+ return {
662
+ type: actor.type,
663
+ accountIdHash: hashSecret(actor.accountId),
664
+ sessionIdHash: actor.sessionId ? hashSecret(actor.sessionId) : undefined,
665
+ };
666
+ }
667
+ function sanitizeTarget(target) {
668
+ return {
669
+ type: target.type,
670
+ id: target.id,
671
+ };
672
+ }
673
+ function sanitizeRequest(request) {
674
+ return {
675
+ requestId: request.requestId,
676
+ jsonMode: request.jsonMode,
677
+ };
678
+ }
679
+ function sanitizeRuntimeIdentity(runtimeIdentity) {
680
+ return {
681
+ runtimeScopeId: runtimeIdentity.runtimeScopeId,
682
+ runtimeVersion: runtimeIdentity.runtimeVersion,
683
+ };
684
+ }
685
+ function sanitizeConfirmationFacts(facts) {
686
+ if (!facts || Object.keys(facts).length === 0) {
687
+ return undefined;
688
+ }
689
+ return Object.fromEntries(Object.entries(facts).filter(([, value]) => ['string', 'boolean', 'number'].includes(typeof value)));
690
+ }
691
+ function hashSecret(secret) {
692
+ return createHash('sha256').update(secret).digest('base64url');
693
+ }
694
+ function auditFactFromRecord(record) {
695
+ return {
696
+ timestamp: record.timestamp,
697
+ operationId: record.operationId,
698
+ operationName: record.operationName,
699
+ result: record.result,
700
+ actor: { ...record.actor },
701
+ origin: record.origin,
702
+ target: { ...record.target },
703
+ request: { ...record.request },
704
+ confirmationFacts: record.confirmationFacts ? { ...record.confirmationFacts } : undefined,
705
+ };
706
+ }
707
+ function getRuntimeScopeMutationState(storageDir, runtimeScopeId) {
708
+ const key = `${storageDir}\0${runtimeScopeId}`;
709
+ const existing = runtimeScopeMutationStates.get(key);
710
+ if (existing) {
711
+ return existing;
712
+ }
713
+ const state = {
714
+ mutationQueue: Promise.resolve(),
715
+ activeMutations: new Map(),
716
+ activePreparations: new Map(),
717
+ idempotency: new Map(),
718
+ recentAuditFacts: [],
719
+ journalUnavailable: false,
720
+ };
721
+ runtimeScopeMutationStates.set(key, state);
722
+ return state;
723
+ }
724
+ //# sourceMappingURL=adminOperationService.js.map