@pulsarinteractive/geniustasker 0.1.0-beta.13 → 0.1.0-beta.14

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.
package/src/commands.mjs CHANGED
@@ -1,5 +1,14 @@
1
+ import {
2
+ feedbackDraftSchema,
3
+ prepareFeedbackCommand,
4
+ readFeedbackCapabilities,
5
+ validateFeedbackCreate,
6
+ validateFeedbackUpload,
7
+ validFeedbackReceipt,
8
+ validFeedbackMediaSession,
9
+ } from './feedback.mjs';
1
10
  import { retryAt, requireRetryReady } from './recovery.mjs';
2
- import { randomUUID } from 'node:crypto';
11
+ import { randomUUID, createHash } from 'node:crypto';
3
12
  import { constants } from 'node:fs';
4
13
  import { open } from 'node:fs/promises';
5
14
  import { join } from 'node:path';
@@ -74,11 +83,12 @@ export function validateCommand(value) {
74
83
  if (
75
84
  Buffer.byteLength(JSON.stringify(command)) > catalog.maxCommandBytes ||
76
85
  Object.keys(command.data).some((key) => !definition.fields.includes(key)) ||
77
- (definition.create ? command.expectedRevision !== null : command.expectedRevision === null)
86
+ (!definition.upsert &&
87
+ (definition.create ? command.expectedRevision !== null : command.expectedRevision === null))
78
88
  ) {
79
89
  fail(
80
90
  'invalid_arguments',
81
- 'Use the declared command fields and size limit. Creation requires a null revision; other commands require the current record revision.',
91
+ 'Use the declared command fields and size limit. Creation requires a null revision; updates require the current record revision. Declared upserts use the revision returned by their dedicated read.',
82
92
  );
83
93
  }
84
94
  const prefix =
@@ -179,7 +189,7 @@ const binding = (session) => ({
179
189
  profileId: session.profile_id,
180
190
  sessionId: session.session_id,
181
191
  });
182
- function checkSavedCommand(row, input, identity) {
192
+ function checkSavedCommand(row, input, identity, protocol) {
183
193
  if (row && (row.formatVersion !== 1 || canonical(row.binding) !== canonical(identity))) {
184
194
  fail(
185
195
  'operation_identity_mismatch',
@@ -190,7 +200,7 @@ function checkSavedCommand(row, input, identity) {
190
200
  },
191
201
  );
192
202
  }
193
- if (row && canonical(row.input) !== canonical(input)) {
203
+ if (row && (row.protocol !== protocol || canonical(row.input) !== canonical(input))) {
194
204
  fail(
195
205
  'idempotency_mismatch',
196
206
  'The operation ID already belongs to a different immutable request.',
@@ -222,6 +232,21 @@ const receiptSchema = z
222
232
  })
223
233
  .strict();
224
234
 
235
+ const confirmationProtocols = {
236
+ feedback_submit: {
237
+ validate: validateFeedbackCreate,
238
+ validReceipt: validFeedbackReceipt,
239
+ operationId: (input) => input.commandId,
240
+ path: '/api/agents/v1/feedback',
241
+ },
242
+ feedback_media_open: {
243
+ validate: validateFeedbackUpload,
244
+ validReceipt: validFeedbackMediaSession,
245
+ operationId: (input) => input.id,
246
+ path: '/api/agents/v1/feedback/media/uploads',
247
+ },
248
+ };
249
+
225
250
  /** A journal is bound to one authenticated terminal identity. Persist the full
226
251
  * request before the network call, never regenerate a UUID after a timeout.
227
252
  * It contains private project text but no access/refresh tokens. A process crash
@@ -261,14 +286,184 @@ export class CommandJournal {
261
286
  return { operationId: input.operationId, state: row?.state ?? 'prepared', request: input };
262
287
  }, this.client.transport.signal);
263
288
  }
289
+ async prepareFeedback(draft) {
290
+ const value = checked(feedbackDraftSchema, draft);
291
+ const identity = binding(await this.client.session());
292
+ if (!value.expectedEpoch) {
293
+ value.expectedEpoch = (await readFeedbackCapabilities(this.client)).epoch;
294
+ }
295
+ if (canonical(binding(await this.client.session())) !== canonical(identity)) {
296
+ fail('operation_identity_mismatch', 'The connection changed while preparing feedback.');
297
+ }
298
+ const prepared = prepareFeedbackCommand(value),
299
+ store = this.store(prepared.command.commandId);
300
+ await store.locked(
301
+ () =>
302
+ store.write({
303
+ formatVersion: 1,
304
+ protocol: 'feedback_submit',
305
+ binding: identity,
306
+ input: prepared.command,
307
+ state: 'prepared',
308
+ }),
309
+ this.client.transport.signal,
310
+ );
311
+ return prepared;
312
+ }
313
+ async submitFeedback(value) {
314
+ return this.#execute(value, 'feedback_submit');
315
+ }
316
+ async openFeedbackMedia(value) {
317
+ return this.#execute(value, 'feedback_media_open');
318
+ }
319
+ async #mediaUploadRow(store, protocol = 'feedback_media_open') {
320
+ const identity = binding(await this.client.session());
321
+ const row = await store.read();
322
+ if (
323
+ !row ||
324
+ row.formatVersion !== 1 ||
325
+ row.input?.id !== store.context ||
326
+ row.protocol !== protocol ||
327
+ row.state !== 'confirmed' ||
328
+ !confirmationProtocols[protocol].validReceipt(row.receipt, row.input)
329
+ ) {
330
+ fail(
331
+ 'operation_not_found',
332
+ 'Confirm the saved upload reservation first. Recover an uncertain reservation with commands retry.',
333
+ );
334
+ }
335
+ if (canonical(row.binding) !== canonical(identity)) {
336
+ fail(
337
+ 'operation_identity_mismatch',
338
+ 'The upload belongs to another connection, profile, session or environment.',
339
+ );
340
+ }
341
+ return { identity, row };
342
+ }
343
+ #confirmedMediaReceipt(row) {
344
+ if (row.uploadState !== 'confirmed') {
345
+ return null;
346
+ }
347
+ if (
348
+ !confirmationProtocols[row.protocol].validReceipt(row.uploadReceipt, row.input) ||
349
+ row.uploadReceipt.state !== 'ready'
350
+ ) {
351
+ fail(
352
+ 'invalid_response',
353
+ 'The saved feedback image receipt is invalid. Inspect the operation before acting.',
354
+ );
355
+ }
356
+ return row.uploadReceipt;
357
+ }
358
+ #requireCurrentMediaSize(row) {
359
+ if (row.input.size > 4_000_000) {
360
+ fail('feedback_media_too_large', 'Use a screenshot no larger than 4,000,000 bytes.', {
361
+ status: 413,
362
+ });
363
+ }
364
+ }
365
+ /** A confirmed upload can be replayed without reopening the source file.
366
+ * The same identity and receipt checks still apply; no HTTP request is made. */
367
+ async confirmedFeedbackMediaUpload(id) {
368
+ return this.#confirmedMediaUpload(id, 'feedback_media_open');
369
+ }
370
+ async #confirmedMediaUpload(id, protocol) {
371
+ const store = this.store(id);
372
+ return store.locked(async () => {
373
+ const { row } = await this.#mediaUploadRow(store, protocol);
374
+ const receipt = this.#confirmedMediaReceipt(row);
375
+ if (!receipt) {
376
+ this.#requireCurrentMediaSize(row);
377
+ }
378
+ return receipt;
379
+ }, this.client.transport.signal);
380
+ }
381
+ /** Binary transfer uses the already-confirmed immutable reservation. It
382
+ * never renews an uncertain reservation or retries another request silently. */
383
+ async uploadFeedbackMediaBytes(id, bytes, sha256) {
384
+ return this.#uploadMediaBytes(id, bytes, sha256, 'feedback_media_open');
385
+ }
386
+ async #uploadMediaBytes(id, bytes, sha256, protocol) {
387
+ const store = this.store(id);
388
+ return store.locked(async () => {
389
+ const { identity, row } = await this.#mediaUploadRow(store, protocol);
390
+ const confirmed = this.#confirmedMediaReceipt(row);
391
+ if (confirmed) {
392
+ return confirmed;
393
+ }
394
+ this.#requireCurrentMediaSize(row);
395
+ const source = row.input;
396
+ if (
397
+ !Buffer.isBuffer(bytes) ||
398
+ bytes.length !== source.size ||
399
+ sha256 !== source.sha256 ||
400
+ createHash('sha256').update(bytes).digest('hex') !== source.sha256
401
+ ) {
402
+ fail(
403
+ 'idempotency_mismatch',
404
+ 'The image bytes changed after preparation. Do not reuse this reservation.',
405
+ );
406
+ }
407
+ requireRetryReady(row.uploadRetryAt);
408
+ const session = await this.client.authorizedSession();
409
+ if (canonical(binding(session)) !== canonical(identity)) {
410
+ fail('operation_identity_mismatch', 'The connection changed before upload.');
411
+ }
412
+ await store.write({ ...row, uploadState: 'uncertain' });
413
+ this.client.invalidateReads?.();
414
+ try {
415
+ const result = await this.client.transport.request(row.receipt.uploadPath, {
416
+ method: 'PUT',
417
+ token: session.access_token,
418
+ bytes,
419
+ });
420
+ if (
421
+ !confirmationProtocols[protocol].validReceipt(result, row.input) ||
422
+ result.state !== 'ready'
423
+ ) {
424
+ fail(
425
+ 'invalid_response',
426
+ 'The feedback image upload receipt is invalid. Retry the same bytes and reservation.',
427
+ { execution: 'unknown' },
428
+ );
429
+ }
430
+ await store.write({ ...row, uploadState: 'confirmed', uploadReceipt: result });
431
+ return result;
432
+ } catch (error) {
433
+ const safe = safeError(error);
434
+ await store
435
+ .write({
436
+ ...row,
437
+ uploadState: 'uncertain',
438
+ uploadRetryAt: retryAt(error),
439
+ uploadError: safe.toJSON(),
440
+ })
441
+ .catch(() => {});
442
+ throw new AgentError(safe.code, safe.message, {
443
+ status: safe.status,
444
+ retryable: safe.retryable,
445
+ ...safe.details,
446
+ execution: 'unknown',
447
+ operationId: id,
448
+ });
449
+ }
450
+ }, this.client.transport.signal);
451
+ }
264
452
  async inspect(id) {
265
453
  const row = await this.store(id).read();
266
- if (!row || row.formatVersion !== 1 || row.input?.operationId !== id) {
454
+ if (
455
+ !row ||
456
+ row.formatVersion !== 1 ||
457
+ (row.protocol
458
+ ? confirmationProtocols[row.protocol]?.operationId(row.input)
459
+ : row.input?.operationId) !== id
460
+ ) {
267
461
  fail('operation_not_found', 'This context has no valid local operation with that ID.');
268
462
  }
269
463
  return {
270
464
  operationId: id,
271
465
  source: 'local_journal',
466
+ ...(row.protocol ? { protocol: row.protocol } : {}),
272
467
  state: row.state,
273
468
  request: row.input,
274
469
  ...(row.receipt ? { receipt: row.receipt } : {}),
@@ -277,16 +472,27 @@ export class CommandJournal {
277
472
  };
278
473
  }
279
474
  async execute(value) {
280
- const input = validateCommand(value),
281
- store = this.store(input.operationId);
475
+ return this.#execute(value);
476
+ }
477
+ async #execute(value, protocol) {
478
+ const typed = protocol ? confirmationProtocols[protocol] : null;
479
+ if (protocol && !typed) {
480
+ fail('invalid_arguments', 'Unknown saved operation protocol.');
481
+ }
482
+ const input = typed ? typed.validate(value) : validateCommand(value),
483
+ operationId = typed ? typed.operationId(input) : input.operationId,
484
+ store = this.store(operationId);
282
485
  return store.locked(async () => {
283
486
  // Capture token and identity together under the refresh lock. A later
284
487
  // logout/login cannot turn this pending operation into another profile.
285
488
  const localSession = await this.client.session(),
286
489
  identity = binding(localSession);
287
490
  let row = await store.read();
288
- checkSavedCommand(row, input, identity);
491
+ checkSavedCommand(row, input, identity, protocol);
289
492
  if (row?.state === 'confirmed') {
493
+ if (typed && !typed.validReceipt(row.receipt, input)) {
494
+ fail('invalid_response', 'Invalid saved feedback receipt.');
495
+ }
290
496
  return { source: 'local_receipt', receipt: row.receipt };
291
497
  }
292
498
  requireRetryReady(row?.retryAt);
@@ -294,17 +500,28 @@ export class CommandJournal {
294
500
  if (canonical(binding(session)) !== canonical(identity)) {
295
501
  fail('operation_identity_mismatch', 'The connection changed before transmission.');
296
502
  }
297
- row = { formatVersion: 1, binding: identity, input, state: 'uncertain' };
503
+ row = {
504
+ formatVersion: 1,
505
+ ...(protocol ? { protocol } : {}),
506
+ binding: identity,
507
+ input,
508
+ state: 'uncertain',
509
+ };
298
510
  await store.write(row);
299
511
  try {
300
- const receipt = await this.client.transport.request('/api/agents/v1/commands', {
301
- method: 'POST',
302
- json: input,
303
- token: session.access_token,
304
- });
512
+ const receipt = await this.client.transport.request(
513
+ typed?.path ?? '/api/agents/v1/commands',
514
+ {
515
+ method: 'POST',
516
+ json: input,
517
+ token: session.access_token,
518
+ },
519
+ );
305
520
  if (
306
- !receiptSchema.safeParse(receipt).success ||
307
- ['operationId', 'scope', 'kind', 'epoch'].some((key) => receipt[key] !== input[key])
521
+ typed
522
+ ? !typed.validReceipt(receipt, input)
523
+ : !receiptSchema.safeParse(receipt).success ||
524
+ ['operationId', 'scope', 'kind', 'epoch'].some((key) => receipt[key] !== input[key])
308
525
  ) {
309
526
  fail(
310
527
  'invalid_response',
@@ -322,7 +539,7 @@ export class CommandJournal {
322
539
  remediation: safe.remediation,
323
540
  execution: 'unknown',
324
541
  ...safe.details,
325
- operationId: input.operationId,
542
+ operationId,
326
543
  });
327
544
  // The uncertainty marker is already durable. Preserve the useful original
328
545
  // error/operation ID even if disk pressure prevents saving diagnostics.
@@ -334,6 +551,7 @@ export class CommandJournal {
334
551
  }, this.client.transport.signal);
335
552
  }
336
553
  async retry(id) {
337
- return this.execute((await this.inspect(id)).request);
554
+ const saved = await this.inspect(id);
555
+ return this.#execute(saved.request, saved.protocol);
338
556
  }
339
557
  }