@playcraft/cli 0.1.49-beta → 0.1.50-beta
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/dist/workspace-runtime/previews/publish.js +16 -7
- package/dist/workspace-runtime/previews/runtime-preview.js +177 -0
- package/dist/workspace-runtime/serve.js +102 -4
- package/dist/workspace-runtime/server/asset-transfers.js +63 -0
- package/dist/workspace-runtime/server/dispatch.js +282 -43
- package/dist/workspace-runtime/server/http.js +32 -8
- package/dist/workspace-runtime/workspaces/asset-transfer-dependencies.js +81 -0
- package/dist/workspace-runtime/workspaces/asset-transfer-publish.js +434 -0
- package/dist/workspace-runtime/workspaces/asset-transfer-storage.js +389 -0
- package/dist/workspace-runtime/workspaces/directory-mutations.js +238 -0
- package/dist/workspace-runtime/workspaces/directory-revisions.js +56 -0
- package/dist/workspace-runtime/workspaces/disk-snapshot.js +3 -3
- package/dist/workspace-runtime/workspaces/json5-edit.js +144 -1
- package/dist/workspace-runtime/workspaces/parameter-agent-inputs.js +87 -0
- package/dist/workspace-runtime/workspaces/parameter-agent-protocol.js +29 -0
- package/dist/workspace-runtime/workspaces/parameter-agent-store.js +58 -0
- package/dist/workspace-runtime/workspaces/parameter-agent.js +282 -0
- package/dist/workspace-runtime/workspaces/parameters.js +77 -54
- package/package.json +3 -3
|
@@ -4,7 +4,7 @@ import { abandonTurnChanges, beginTurnChanges, finishTurnChanges } from '../work
|
|
|
4
4
|
import { shareWorkspaceGit } from '../workspaces/shared-git.js';
|
|
5
5
|
import { join } from 'node:path';
|
|
6
6
|
import { z } from 'zod';
|
|
7
|
-
import { fileWritePayloadSchema, fileBinaryWritePayloadSchema, directoryCreatePayloadSchema, gitCommitPayloadSchema, gitPathsPayloadSchema, gitPushPayloadSchema, gitPullPayloadSchema, gitMergeAbortPayloadSchema, parameterPatchPayloadSchema, productionSessionAttemptId, reasoningEffortSchema, workspacePermissionModeSchema, workspaceComposerSelectionSchema, workspaceReviewPayloadSchema, workspaceCompactPayloadSchema, workspaceSteerPayloadSchema, workspaceApprovalResponseSchema, terminalCreatePayloadSchema, terminalProcessIdentity, transitionOperation, recoverUncertainOperation, workspaceSavePayloadSchema, workspaceSkillsUpdatePayloadSchema, workspaceRemixReferenceImportPayloadSchema, deliveryBuildPayloadSchema, deliveryCancelPayloadSchema, } from '@playcraft/common/cloud-workspace/runtime';
|
|
7
|
+
import { fileWritePayloadSchema, fileBinaryWritePayloadSchema, directoryCreatePayloadSchema, directoryRenamePayloadSchema, directoryDeletePayloadSchema, directoryMutationReceiptSchema, gitCommitPayloadSchema, gitPathsPayloadSchema, gitPushPayloadSchema, gitPullPayloadSchema, gitMergeAbortPayloadSchema, parameterPatchPayloadSchema, parameterAgentTaskRequestSchema, parameterAgentVerifyPayloadSchema, productionSessionAttemptId, reasoningEffortSchema, workspacePermissionModeSchema, workspaceComposerSelectionSchema, workspaceReviewPayloadSchema, workspaceCompactPayloadSchema, workspaceSteerPayloadSchema, workspaceApprovalResponseSchema, terminalCreatePayloadSchema, terminalProcessIdentity, transitionOperation, recoverUncertainOperation, workspaceSavePayloadSchema, workspaceSkillsUpdatePayloadSchema, workspaceRemixReferenceImportPayloadSchema, deliveryBuildPayloadSchema, deliveryCancelPayloadSchema, } from '@playcraft/common/cloud-workspace/runtime';
|
|
8
8
|
import { closeCliCredentials, ensureCliCredentials } from '../workspaces/cli-credentials.js';
|
|
9
9
|
import { artifactFormat } from '../workspaces/artifact-files.js';
|
|
10
10
|
import { refreshWorkspaceArtifacts } from '../workspaces/artifact-events.js';
|
|
@@ -24,6 +24,7 @@ import { InvalidWorkspacePathError, resolveWorkspaceFile, writeWorkspaceFile, }
|
|
|
24
24
|
import { GitWorkspaceError, commitWorkspaceGit, discardWorkspaceGit, pushWorkspaceGit, pullWorkspaceGit, abortWorkspaceMerge, saveWorkspaceGit, stageWorkspaceGit, unstageWorkspaceGit, } from '../workspaces/git.js';
|
|
25
25
|
import { ParameterEditError } from '../workspaces/json5-edit.js';
|
|
26
26
|
import { patchWorkspaceParameters, readWorkspaceParameters } from '../workspaces/parameters.js';
|
|
27
|
+
import { prepareParameterAgentTask, finishParameterAgentTask, verifyParameterAgentTask, } from '../workspaces/parameter-agent.js';
|
|
27
28
|
import { previewFailureCode, previewWorkspaceRoot, runPreviewPublish, trackPreviewPublish, } from '../previews/publish.js';
|
|
28
29
|
import { spawnBackgroundWriter, stopBackgroundWriter, } from '../processes/managed-writes.js';
|
|
29
30
|
import { wakeSourceEventUploader } from './source-uploader.js';
|
|
@@ -31,6 +32,10 @@ import { batchDirectoryHeld } from '../batch/occupancy.js';
|
|
|
31
32
|
import { BinaryWorkspaceWriteError, observeWorkspaceBinaryFile, writeWorkspaceBinaryFile } from '../workspaces/binary-write.js';
|
|
32
33
|
import { importWorkspaceLibraryAssets } from '../workspaces/asset-library-import.js';
|
|
33
34
|
import { createWorkspaceDirectory, WorkspaceDirectoryCreateError } from '../workspaces/directory-create.js';
|
|
35
|
+
import { DirectoryMutationError, mutateWorkspaceDirectory } from '../workspaces/directory-mutations.js';
|
|
36
|
+
import { observeWorkspaceDirectories } from '../workspaces/directory-revisions.js';
|
|
37
|
+
import { publishAssetTransfer } from '../workspaces/asset-transfer-publish.js';
|
|
38
|
+
import { AssetTransferError } from '../workspaces/asset-transfer-storage.js';
|
|
34
39
|
import { runDeliveryBuild, cancelDeliveryBuild, trackDeliveryBuild, DeliveryBuildError } from '../workspaces/delivery-build.js';
|
|
35
40
|
const CONVERSATION_KINDS = new Set([
|
|
36
41
|
'session.create',
|
|
@@ -47,7 +52,10 @@ const LOCAL_KINDS = new Set([
|
|
|
47
52
|
'file.write',
|
|
48
53
|
'file.binary.write',
|
|
49
54
|
'asset.library.import',
|
|
55
|
+
'asset.bundle.save',
|
|
50
56
|
'directory.create',
|
|
57
|
+
'directory.rename',
|
|
58
|
+
'directory.delete',
|
|
51
59
|
'git.commit',
|
|
52
60
|
'git.push',
|
|
53
61
|
'git.pull',
|
|
@@ -59,11 +67,30 @@ const LOCAL_KINDS = new Set([
|
|
|
59
67
|
'workspace.references.import',
|
|
60
68
|
'terminal.create',
|
|
61
69
|
'parameter.patch',
|
|
70
|
+
'parameter.verify',
|
|
62
71
|
'preview.publish',
|
|
63
72
|
'delivery.build',
|
|
64
73
|
'delivery.cancel',
|
|
65
74
|
'skills.update',
|
|
66
75
|
]);
|
|
76
|
+
const parameterVerifications = new WeakMap();
|
|
77
|
+
const parameterVerificationClosing = new WeakSet();
|
|
78
|
+
export async function stopParameterVerifications(state) {
|
|
79
|
+
parameterVerificationClosing.add(state);
|
|
80
|
+
const tasks = parameterVerifications.get(state);
|
|
81
|
+
if (!tasks)
|
|
82
|
+
return;
|
|
83
|
+
for (const controller of tasks.keys())
|
|
84
|
+
controller.abort();
|
|
85
|
+
await Promise.allSettled(tasks.values());
|
|
86
|
+
}
|
|
87
|
+
export async function recoverInterruptedParameterVerifications(journal) {
|
|
88
|
+
for (const { scopeKey, operation } of journal.listOperations()) {
|
|
89
|
+
if (operation.kind !== 'parameter.verify' || !['queued', 'dispatched', 'accepted', 'uncertain'].includes(operation.status))
|
|
90
|
+
continue;
|
|
91
|
+
await journal.putOperation(scopeKey, transitionOperation(operation, 'interrupted', { error: 'parameter_verification_interrupted' }));
|
|
92
|
+
}
|
|
93
|
+
}
|
|
67
94
|
export function canExecuteKind(state, kind) {
|
|
68
95
|
if (LOCAL_KINDS.has(kind))
|
|
69
96
|
return true;
|
|
@@ -107,9 +134,15 @@ async function executeScopedOperation(state, scopeKey, operation, payload, recov
|
|
|
107
134
|
if (operation.kind === 'asset.library.import') {
|
|
108
135
|
return executeAssetLibraryImport(state, scopeKey, current, payload);
|
|
109
136
|
}
|
|
137
|
+
if (operation.kind === 'asset.bundle.save') {
|
|
138
|
+
return executeAssetBundleSave(state, scopeKey, current, payload);
|
|
139
|
+
}
|
|
110
140
|
if (operation.kind === 'directory.create') {
|
|
111
141
|
return executeDirectoryCreate(state, scopeKey, current, payload);
|
|
112
142
|
}
|
|
143
|
+
if (operation.kind === 'directory.rename' || operation.kind === 'directory.delete') {
|
|
144
|
+
return executeDirectoryMutation(state, scopeKey, current, payload);
|
|
145
|
+
}
|
|
113
146
|
if (operation.kind === 'workspace.references.import') {
|
|
114
147
|
return executeRemixReferenceImport(state, scopeKey, current, payload);
|
|
115
148
|
}
|
|
@@ -140,6 +173,9 @@ async function executeScopedOperation(state, scopeKey, operation, payload, recov
|
|
|
140
173
|
if (operation.kind === 'parameter.patch') {
|
|
141
174
|
return executeParameterPatch(state, scopeKey, current, payload);
|
|
142
175
|
}
|
|
176
|
+
if (operation.kind === 'parameter.verify') {
|
|
177
|
+
return executeParameterVerify(state, scopeKey, current, payload);
|
|
178
|
+
}
|
|
143
179
|
if (operation.kind === 'preview.publish') {
|
|
144
180
|
return executePreviewPublish(state, scopeKey, current);
|
|
145
181
|
}
|
|
@@ -321,6 +357,19 @@ async function executeTurn(state, scopeKey, operation, payload, recovery) {
|
|
|
321
357
|
if (!mode.success)
|
|
322
358
|
return persist(state, scopeKey, transitionOperation(operation, 'failed', { error: 'invalid_permission_mode' }));
|
|
323
359
|
const requestedMode = mode.data ?? found?.permissionMode ?? recovery?.permissionMode ?? 'auto';
|
|
360
|
+
const parameterTask = parameterAgentTaskRequestSchema.optional().safeParse(body.parameterTask);
|
|
361
|
+
if (!parameterTask.success || (parameterTask.data && parameterTask.data.taskId !== operation.clientRequestId))
|
|
362
|
+
return persist(state, scopeKey, transitionOperation(operation, 'failed', { error: 'invalid_parameter_task' }));
|
|
363
|
+
if (parameterTask.data) {
|
|
364
|
+
if (operation.directoryName === 'root')
|
|
365
|
+
return persist(state, scopeKey, transitionOperation(operation, 'failed', { error: 'invalid_workspace_directory' }));
|
|
366
|
+
if ((selection.data.workMode ?? 'execute') !== 'execute' || requestedMode === 'read-only')
|
|
367
|
+
return persist(state, scopeKey, transitionOperation(operation, 'failed', { error: 'parameter_task_readonly' }));
|
|
368
|
+
if (workspaceSessions(state, operation.workspaceId, operation.directoryName).some(sessionTurnBusy))
|
|
369
|
+
return persist(state, scopeKey, transitionOperation(operation, 'failed', { error: 'turn_already_active' }));
|
|
370
|
+
if (await batchDirectoryHeld(state, operation.workspaceId, operation.directoryName))
|
|
371
|
+
return persist(state, scopeKey, transitionOperation(operation, 'failed', { error: 'batch_workspace_readonly' }));
|
|
372
|
+
}
|
|
324
373
|
const modelChanged = selected.data !== undefined && selected.data !== (found?.modelConfigId ?? recovery?.modelConfigId);
|
|
325
374
|
const requestedEffort = effort.data ?? (modelChanged ? undefined : recovery?.reasoningEffort ?? found?.reasoningEffort);
|
|
326
375
|
if (recovery && found?.recoverability !== 'native') {
|
|
@@ -392,49 +441,72 @@ async function executeTurn(state, scopeKey, operation, payload, recovery) {
|
|
|
392
441
|
return persist(state, scopeKey, transitionOperation(operation, 'failed', { error: 'cli_credentials_unavailable' }));
|
|
393
442
|
}
|
|
394
443
|
}
|
|
444
|
+
let parameterInstructions = '';
|
|
445
|
+
if (parameterTask.data) {
|
|
446
|
+
try {
|
|
447
|
+
parameterInstructions = (await prepareParameterAgentTask(state, operation, parameterTask.data, root)).instructions;
|
|
448
|
+
}
|
|
449
|
+
catch (error) {
|
|
450
|
+
return persist(state, scopeKey, transitionOperation(operation, 'failed', { error: parameterAgentError(error) }));
|
|
451
|
+
}
|
|
452
|
+
}
|
|
395
453
|
// Taken before the native turn exists, so nothing the agent writes can precede it.
|
|
396
454
|
await beginTurnChanges(state, sessionId, {
|
|
397
455
|
root, workspaceId: operation.workspaceId, directoryName: binding.directoryName ?? 'basic',
|
|
398
456
|
});
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
457
|
+
let result;
|
|
458
|
+
try {
|
|
459
|
+
result = await native(state).startTurn({
|
|
460
|
+
sessionId,
|
|
461
|
+
threadId: binding.threadId,
|
|
462
|
+
text: composer.append(batchContext + context + String(body.text ?? '') + attachmentText, [engineeringBatchContext, parameterInstructions].filter(Boolean).join('\n\n')),
|
|
463
|
+
images: attachments.filter((file) => ['image/png', 'image/jpeg', 'image/gif', 'image/webp'].includes(file.mimeType)).map((file) => file.path),
|
|
464
|
+
clientRequestId: operation.clientRequestId,
|
|
465
|
+
modelConfigId: selected.data ?? binding.modelConfigId,
|
|
466
|
+
reasoningEffort: requestedEffort,
|
|
467
|
+
permissionMode: requestedMode,
|
|
468
|
+
workMode: selection.data.workMode ?? 'execute',
|
|
469
|
+
skillsLockHash: composer.skillsLockHash,
|
|
470
|
+
uiSnapshot: uiSnapshot.data,
|
|
471
|
+
simulateLostReceipt: body.simulateLostReceipt === true,
|
|
472
|
+
persistReservation: async ({ nativeRequestId, modelConfigId, reasoningEffort, permissionMode }) => {
|
|
473
|
+
const selectedEffort = reasoningEffort ?? requestedEffort;
|
|
474
|
+
const selectedMode = permissionMode ?? requestedMode;
|
|
475
|
+
await persist(state, scopeKey, {
|
|
476
|
+
...operation,
|
|
477
|
+
nativeRequestId,
|
|
478
|
+
nativeThreadId: binding.threadId,
|
|
479
|
+
modelConfigId,
|
|
480
|
+
reasoningEffort: selectedEffort,
|
|
481
|
+
permissionMode: selectedMode,
|
|
482
|
+
workMode: selection.data.workMode ?? 'execute',
|
|
483
|
+
context: composer.context,
|
|
484
|
+
userText: selection.data.workMode !== undefined || composer.context !== undefined || parameterTask.data
|
|
485
|
+
? String(body.userText ?? body.text ?? '') : undefined,
|
|
486
|
+
updatedAt: new Date().toISOString(),
|
|
487
|
+
});
|
|
488
|
+
await state.journal.putSession({ ...binding, modelConfigId, reasoningEffort: selectedEffort, permissionMode: selectedMode, turnStatus: 'starting' });
|
|
489
|
+
},
|
|
490
|
+
});
|
|
491
|
+
}
|
|
492
|
+
catch (error) {
|
|
493
|
+
if (!parameterTask.data)
|
|
494
|
+
throw error;
|
|
495
|
+
abandonTurnChanges(state, sessionId);
|
|
496
|
+
if (error instanceof NativePreparationError) {
|
|
497
|
+
await state.journal.putSession({ ...(state.journal.getSession(sessionId) ?? binding), turnStatus: undefined, turnBlock: undefined });
|
|
498
|
+
return persist(state, scopeKey, transitionOperation(state.journal.getOperation(scopeKey) ?? operation, 'failed', { error: error.message }));
|
|
499
|
+
}
|
|
500
|
+
await state.journal.putSession({ ...(state.journal.getSession(sessionId) ?? binding), turnStatus: 'starting', turnBlock: 'uncertain' });
|
|
501
|
+
return persist(state, scopeKey, transitionOperation(state.journal.getOperation(scopeKey) ?? operation, 'uncertain', { error: 'native_receipt_lost' }));
|
|
502
|
+
}
|
|
431
503
|
const reserved = state.journal.getOperation(scopeKey) ?? operation;
|
|
432
504
|
if (result.outcome === 'uncertain' || result.outcome === 'failed' || !result.turnId) {
|
|
433
505
|
abandonTurnChanges(state, sessionId);
|
|
434
506
|
const failed = result.outcome === 'failed';
|
|
435
507
|
// Codex no longer knows the thread although the binding said it could continue. Marking the
|
|
436
508
|
// binding lost lets the same turn, sent again with the conversation, rebind the session.
|
|
437
|
-
const threadLost = failed && result.error === 'unknown_thread';
|
|
509
|
+
const threadLost = result.outcome === 'failed' && result.error === 'unknown_thread';
|
|
438
510
|
await state.journal.putSession({
|
|
439
511
|
...(state.journal.getSession(sessionId) ?? binding),
|
|
440
512
|
turnStatus: failed ? undefined : 'starting',
|
|
@@ -480,7 +552,7 @@ async function executeTurn(state, scopeKey, operation, payload, recovery) {
|
|
|
480
552
|
threadId: binding.threadId,
|
|
481
553
|
turnId: result.turnId,
|
|
482
554
|
});
|
|
483
|
-
if (selection.data.workMode !== undefined || composer.context !== undefined) {
|
|
555
|
+
if (selection.data.workMode !== undefined || composer.context !== undefined || parameterTask.data) {
|
|
484
556
|
await recordNativeEvents(state, accepted, [{
|
|
485
557
|
type: 'composer.context', occurredAt: new Date().toISOString(), payload: {
|
|
486
558
|
threadId: binding.threadId, turnId: result.turnId, clientRequestId: operation.clientRequestId,
|
|
@@ -497,7 +569,56 @@ async function executeTurn(state, scopeKey, operation, payload, recovery) {
|
|
|
497
569
|
const session = state.journal.getSession(sessionId) ?? binding;
|
|
498
570
|
await state.journal.putSession({ ...session, turnStatus: 'waiting_for_user', activeTurnId: result.turnId });
|
|
499
571
|
}
|
|
500
|
-
|
|
572
|
+
const final = state.journal.getOperation(scopeKey) ?? latest;
|
|
573
|
+
await syncParameterAgentOperation(state, final);
|
|
574
|
+
return final;
|
|
575
|
+
}
|
|
576
|
+
async function executeParameterVerify(state, scopeKey, operation, payload) {
|
|
577
|
+
const parsed = parameterAgentVerifyPayloadSchema.safeParse(payload);
|
|
578
|
+
if (!parsed.success)
|
|
579
|
+
return persist(state, scopeKey, transitionOperation(operation, 'failed', { error: 'invalid_parameter_task' }));
|
|
580
|
+
if (operation.directoryName === 'root' || (operation.sessionId && productionSessionAttemptId(operation.sessionId)))
|
|
581
|
+
return persist(state, scopeKey, transitionOperation(operation, 'failed', { error: 'invalid_workspace_directory' }));
|
|
582
|
+
if (workspaceSessions(state, operation.workspaceId, operation.directoryName).some(sessionTurnBusy))
|
|
583
|
+
return persist(state, scopeKey, transitionOperation(operation, 'failed', { error: 'turn_already_active' }));
|
|
584
|
+
if (await batchDirectoryHeld(state, operation.workspaceId, operation.directoryName))
|
|
585
|
+
return persist(state, scopeKey, transitionOperation(operation, 'failed', { error: 'batch_workspace_readonly' }));
|
|
586
|
+
const root = await workspaceRoot(state, operation.workspaceId, operation.directoryName);
|
|
587
|
+
const accepted = await persist(state, scopeKey, transitionOperation(operation, 'accepted'));
|
|
588
|
+
const controller = new AbortController();
|
|
589
|
+
const assertActive = () => {
|
|
590
|
+
if (controller.signal.aborted || parameterVerificationClosing.has(state))
|
|
591
|
+
throw new Error('parameter_verification_interrupted');
|
|
592
|
+
if (state.journal.destroyed())
|
|
593
|
+
throw new Error('runtime_destroyed');
|
|
594
|
+
if ((operation.leaseFence ?? 0) < state.acceptedLeaseFence)
|
|
595
|
+
throw new Error('stale_lease');
|
|
596
|
+
};
|
|
597
|
+
const key = `workspace:${revisionScope(state, operation.workspaceId, operation.directoryName) ?? 'single'}`;
|
|
598
|
+
const task = state.journal.exclusive(key, async () => {
|
|
599
|
+
try {
|
|
600
|
+
assertActive();
|
|
601
|
+
if (workspaceSessions(state, operation.workspaceId, operation.directoryName).some(sessionTurnBusy))
|
|
602
|
+
throw new Error('turn_already_active');
|
|
603
|
+
if (await batchDirectoryHeld(state, operation.workspaceId, operation.directoryName))
|
|
604
|
+
throw new Error('batch_workspace_readonly');
|
|
605
|
+
const result = await verifyParameterAgentTask(state, operation, parsed.data, root, { assertActive, signal: controller.signal });
|
|
606
|
+
assertActive();
|
|
607
|
+
await persist(state, scopeKey, transitionOperation(accepted, 'completed', { result }));
|
|
608
|
+
}
|
|
609
|
+
catch (error) {
|
|
610
|
+
await persist(state, scopeKey, transitionOperation(accepted, 'failed', { error: parameterAgentError(error) }));
|
|
611
|
+
}
|
|
612
|
+
});
|
|
613
|
+
const tasks = parameterVerifications.get(state) ?? new Map();
|
|
614
|
+
parameterVerifications.set(state, tasks);
|
|
615
|
+
const tracked = task.catch(() => undefined).finally(() => tasks.delete(controller));
|
|
616
|
+
tasks.set(controller, tracked);
|
|
617
|
+
return accepted;
|
|
618
|
+
}
|
|
619
|
+
function parameterAgentError(error) {
|
|
620
|
+
return error instanceof Error && /^(?:parameter_|invalid_parameter_|runtime_destroyed$|stale_lease$|turn_already_active$|batch_workspace_readonly$)/.test(error.message)
|
|
621
|
+
? error.message : 'parameter_task_failed';
|
|
501
622
|
}
|
|
502
623
|
/**
|
|
503
624
|
* Gives a session whose native thread was lost a thread in this process. It keeps its own thread
|
|
@@ -742,6 +863,7 @@ async function executeApproval(state, scopeKey, operation, payload) {
|
|
|
742
863
|
}
|
|
743
864
|
async function executeDestroy(state, scopeKey, operation) {
|
|
744
865
|
await state.journal.markDestroyed();
|
|
866
|
+
await stopParameterVerifications(state);
|
|
745
867
|
await closeCliCredentials(state);
|
|
746
868
|
await state.gitCredentials?.destroy();
|
|
747
869
|
disposeTerminalHost(state);
|
|
@@ -792,6 +914,50 @@ async function executeDirectoryCreate(state, scopeKey, operation, payload) {
|
|
|
792
914
|
return persist(state, scopeKey, transitionOperation(operation, 'failed', { error: code }));
|
|
793
915
|
}
|
|
794
916
|
}
|
|
917
|
+
async function executeDirectoryMutation(state, scopeKey, operation, payload) {
|
|
918
|
+
const kind = operation.kind === 'directory.rename' ? 'directory.rename' : 'directory.delete';
|
|
919
|
+
const parsed = kind === 'directory.rename' ? directoryRenamePayloadSchema.safeParse(payload) : directoryDeletePayloadSchema.safeParse(payload);
|
|
920
|
+
if (!parsed.success)
|
|
921
|
+
return persist(state, scopeKey, transitionOperation(operation, 'failed', { error: 'invalid_workspace_path' }));
|
|
922
|
+
let current = operation;
|
|
923
|
+
try {
|
|
924
|
+
const assertCurrent = async () => {
|
|
925
|
+
if ((operation.leaseFence ?? 0) < state.acceptedLeaseFence || state.journal.destroyed())
|
|
926
|
+
throw new DirectoryMutationError('stale_lease');
|
|
927
|
+
if (operation.sessionId && productionSessionAttemptId(operation.sessionId))
|
|
928
|
+
throw new DirectoryMutationError('production_session_readonly');
|
|
929
|
+
if (await batchDirectoryHeld(state, operation.workspaceId, operation.directoryName))
|
|
930
|
+
throw new DirectoryMutationError('batch_workspace_readonly');
|
|
931
|
+
};
|
|
932
|
+
await assertCurrent();
|
|
933
|
+
const root = await workspaceRoot(state, operation.workspaceId, operation.directoryName);
|
|
934
|
+
const scope = revisionScope(state, operation.workspaceId, operation.directoryName);
|
|
935
|
+
const options = { operationId: operation.operationId, operationPayloadHash: operation.payloadHash, scope: scopeKey, assertCurrent,
|
|
936
|
+
observeRevision: async () => (await observeWorkspaceDirectories(root, state.journal, scope)).directoryRevisions?.[parsed.data.path],
|
|
937
|
+
onDetached: async () => { if (current.status === 'dispatched')
|
|
938
|
+
current = await persist(state, scopeKey, transitionOperation(current, 'accepted')); } };
|
|
939
|
+
const receipt = await mutateWorkspaceDirectory(root, kind, parsed.data, options);
|
|
940
|
+
if (!receipt)
|
|
941
|
+
throw new DirectoryMutationError('directory_recovery_required');
|
|
942
|
+
await observeWorkspaceDirectories(root, state.journal, scope);
|
|
943
|
+
const paths = [receipt.path, ...(receipt.newPath ? [receipt.newPath] : [])];
|
|
944
|
+
const result = { paths, skippedPaths: [], failures: [], directoryMutation: directoryMutationReceiptSchema.parse(receipt) };
|
|
945
|
+
if (current.status === 'dispatched')
|
|
946
|
+
current = await persist(state, scopeKey, transitionOperation(current, 'accepted', { result }));
|
|
947
|
+
await recordNativeEvents(state, current, [{ type: 'files.changed', occurredAt: new Date().toISOString(), payload: {
|
|
948
|
+
workspaceId: operation.workspaceId, directoryName: operation.directoryName ?? 'basic', paths,
|
|
949
|
+
source: kind, operationId: operation.operationId, revision: receipt.revision,
|
|
950
|
+
} }]);
|
|
951
|
+
return persist(state, scopeKey, transitionOperation(current, 'completed', { result }));
|
|
952
|
+
}
|
|
953
|
+
catch (error) {
|
|
954
|
+
const code = error instanceof DirectoryMutationError ? error.code
|
|
955
|
+
: error instanceof InvalidWorkspacePathError || error?.code === 'invalid_workspace_path' ? 'invalid_workspace_path'
|
|
956
|
+
: ['EACCES', 'EPERM'].includes(String(error?.code)) ? 'workspace_permission_denied'
|
|
957
|
+
: 'directory_recovery_required';
|
|
958
|
+
return persist(state, scopeKey, transitionOperation(current, code === 'directory_recovery_required' ? 'uncertain' : 'failed', { error: code }));
|
|
959
|
+
}
|
|
960
|
+
}
|
|
795
961
|
async function executeAssetLibraryImport(state, scopeKey, operation, payload) {
|
|
796
962
|
const input = payload;
|
|
797
963
|
try {
|
|
@@ -833,6 +999,63 @@ async function executeAssetLibraryImport(state, scopeKey, operation, payload) {
|
|
|
833
999
|
}));
|
|
834
1000
|
}
|
|
835
1001
|
}
|
|
1002
|
+
async function executeAssetBundleSave(state, scopeKey, operation, payload) {
|
|
1003
|
+
const directoryName = operation.directoryName ?? 'basic';
|
|
1004
|
+
const scope = revisionScope(state, operation.workspaceId, directoryName);
|
|
1005
|
+
const revisions = new Map();
|
|
1006
|
+
const metadata = new Map();
|
|
1007
|
+
try {
|
|
1008
|
+
const assertCurrent = async () => {
|
|
1009
|
+
if (state.journal.destroyed() || (operation.leaseFence ?? 0) < state.acceptedLeaseFence)
|
|
1010
|
+
throw new AssetTransferError(state.journal.destroyed() ? 'runtime_destroyed' : 'stale_lease');
|
|
1011
|
+
if (directoryName === 'root' || operation.sessionId && productionSessionAttemptId(operation.sessionId))
|
|
1012
|
+
throw new AssetTransferError('production_session_readonly');
|
|
1013
|
+
if (await batchDirectoryHeld(state, operation.workspaceId, directoryName))
|
|
1014
|
+
throw new AssetTransferError('batch_workspace_readonly');
|
|
1015
|
+
};
|
|
1016
|
+
await assertCurrent();
|
|
1017
|
+
const root = await workspaceRoot(state, operation.workspaceId, directoryName);
|
|
1018
|
+
const receipt = await publishAssetTransfer(root, { environment: state.config.environment, userId: state.config.userId,
|
|
1019
|
+
workspaceId: operation.workspaceId ?? '', directoryName }, payload, { operationId: operation.operationId, assertCurrent,
|
|
1020
|
+
onManifest: manifest => { for (const file of manifest.files)
|
|
1021
|
+
metadata.set(file.path, file); },
|
|
1022
|
+
assertRevision: async (file, observed) => {
|
|
1023
|
+
const previous = state.journal.fileRevisions(scope)[file.path];
|
|
1024
|
+
const hash = observed?.contentHash ?? '';
|
|
1025
|
+
const revision = previous ? previous.revision + (previous.contentHash === hash ? 0 : 1) : 0;
|
|
1026
|
+
if (previous && previous.contentHash !== hash || !previous && observed)
|
|
1027
|
+
await state.journal.putFileRevision(file.path, { revision, contentHash: hash }, scope);
|
|
1028
|
+
if (file.expectedRevision !== undefined && file.expectedRevision !== revision)
|
|
1029
|
+
throw new AssetTransferError('revision_conflict');
|
|
1030
|
+
revisions.set(file.path, revision + 1);
|
|
1031
|
+
} });
|
|
1032
|
+
await assertCurrent();
|
|
1033
|
+
const paths = [...receipt.files.map(file => file.path), ...(receipt.directories ?? [])];
|
|
1034
|
+
const result = { paths, skippedPaths: [], failures: [], bundleReceipt: receipt };
|
|
1035
|
+
const events = [];
|
|
1036
|
+
for (const file of receipt.files) {
|
|
1037
|
+
const previous = state.journal.fileRevisions(scope)[file.path];
|
|
1038
|
+
const revision = revisions.get(file.path) ?? (previous ? previous.revision + (previous.contentHash === file.contentHash ? 0 : 1) : 1);
|
|
1039
|
+
await state.journal.putFileRevision(file.path, { revision, contentHash: file.contentHash }, scope);
|
|
1040
|
+
events.push({ type: 'file.written', payload: { ...file, revision, writer: 'manual', workspaceId: operation.workspaceId,
|
|
1041
|
+
directoryName, operationId: operation.operationId, transferId: receipt.transferId,
|
|
1042
|
+
...(metadata.get(file.path)?.processing ? { processing: metadata.get(file.path).processing } : {}) }, occurredAt: new Date().toISOString() });
|
|
1043
|
+
}
|
|
1044
|
+
events.push({ type: 'files.changed', payload: { workspaceId: operation.workspaceId, directoryName,
|
|
1045
|
+
operationId: operation.operationId, paths, source: 'asset.bundle.save' }, occurredAt: new Date().toISOString() });
|
|
1046
|
+
const accepted = await persist(state, scopeKey, transitionOperation(operation, 'accepted', { result }));
|
|
1047
|
+
await recordNativeEvents(state, accepted, events);
|
|
1048
|
+
if (operation.workspaceId && directoryName === 'basic')
|
|
1049
|
+
await refreshWorkspaceArtifacts(state, operation.workspaceId, { paths, source: { kind: 'discovered', tool: 'asset.bundle.save', operationId: operation.operationId } }).catch(() => undefined);
|
|
1050
|
+
return persist(state, scopeKey, transitionOperation(accepted, 'completed', { result }));
|
|
1051
|
+
}
|
|
1052
|
+
catch (error) {
|
|
1053
|
+
const code = error instanceof AssetTransferError ? error.code
|
|
1054
|
+
: error.name === 'ZodError' ? 'invalid_asset_transfer'
|
|
1055
|
+
: ['EACCES', 'EPERM'].includes(String(error.code)) ? 'workspace_permission_denied' : 'asset_bundle_save_failed';
|
|
1056
|
+
return persist(state, scopeKey, transitionOperation(operation, 'failed', { error: code }));
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
836
1059
|
async function executeFileBinaryWrite(state, scopeKey, operation, payload) {
|
|
837
1060
|
const parsed = fileBinaryWritePayloadSchema.safeParse(payload);
|
|
838
1061
|
if (!parsed.success)
|
|
@@ -1118,19 +1341,19 @@ async function executeParameterPatch(state, scopeKey, operation, payload) {
|
|
|
1118
1341
|
const root = await workspaceRoot(state, operation.workspaceId, operation.directoryName);
|
|
1119
1342
|
const scope = revisionScope(state, operation.workspaceId, operation.directoryName);
|
|
1120
1343
|
const document = await readWorkspaceParameters(root, state.journal.fileRevisions(scope));
|
|
1121
|
-
if (document.status === 'missing' || document.status === 'schema_only' || !document.dataPath) {
|
|
1122
|
-
return persist(state, scopeKey, transitionOperation(operation, 'failed', { error: 'parameter_data_missing' }));
|
|
1123
|
-
}
|
|
1124
1344
|
if (document.status === 'invalid') {
|
|
1125
1345
|
return persist(state, scopeKey, transitionOperation(operation, 'failed', { error: 'parameter_document_invalid' }));
|
|
1126
1346
|
}
|
|
1347
|
+
if (document.status === 'missing' || document.status === 'schema_only' || !document.dataPath) {
|
|
1348
|
+
return persist(state, scopeKey, transitionOperation(operation, 'failed', { error: 'parameter_data_missing' }));
|
|
1349
|
+
}
|
|
1127
1350
|
const dataPath = document.dataPath;
|
|
1128
|
-
return withObservedFile(state, operation.workspaceId, dataPath, async ({ revision: currentRevision }) => {
|
|
1351
|
+
return withObservedFile(state, operation.workspaceId, dataPath, async ({ revision: currentRevision, file }) => {
|
|
1129
1352
|
if (parsed.data.expectedRevision !== currentRevision) {
|
|
1130
1353
|
return persist(state, scopeKey, transitionOperation(operation, 'failed', { error: 'revision_conflict' }));
|
|
1131
1354
|
}
|
|
1132
1355
|
try {
|
|
1133
|
-
const written = await patchWorkspaceParameters(root, state.journal.fileRevisions(scope), parsed.data);
|
|
1356
|
+
const written = await patchWorkspaceParameters(root, state.journal.fileRevisions(scope), parsed.data, { dataPath, contentHash: file?.contentHash ?? '' });
|
|
1134
1357
|
const revision = currentRevision + 1;
|
|
1135
1358
|
await state.journal.putFileRevision(dataPath, { revision, contentHash: written.contentHash }, scope);
|
|
1136
1359
|
const accepted = await persist(state, scopeKey, transitionOperation(operation, 'accepted', { expectedRevision: revision }));
|
|
@@ -1142,7 +1365,9 @@ async function executeParameterPatch(state, scopeKey, operation, payload) {
|
|
|
1142
1365
|
revision,
|
|
1143
1366
|
contentHash: written.contentHash,
|
|
1144
1367
|
size: written.size,
|
|
1145
|
-
|
|
1368
|
+
...('changes' in parsed.data
|
|
1369
|
+
? { fieldPaths: parsed.data.changes.map((change) => change.fieldPath) }
|
|
1370
|
+
: { fieldPath: parsed.data.fieldPath }),
|
|
1146
1371
|
},
|
|
1147
1372
|
occurredAt: new Date().toISOString(),
|
|
1148
1373
|
},
|
|
@@ -1325,6 +1550,11 @@ export async function ingestCollected(state, event, publish = true) {
|
|
|
1325
1550
|
itemId: ids.itemId,
|
|
1326
1551
|
occurredAt: event.occurredAt,
|
|
1327
1552
|
});
|
|
1553
|
+
if (ids.turnId && ids.threadId) {
|
|
1554
|
+
const operation = state.journal.listOperations().map(item => item.operation).find(item => item.kind === 'session.turn' && item.nativeThreadId === ids.threadId && item.nativeTurnId === ids.turnId);
|
|
1555
|
+
if (operation)
|
|
1556
|
+
await syncParameterAgentOperation(state, operation);
|
|
1557
|
+
}
|
|
1328
1558
|
if (publish && recorded.length > 0)
|
|
1329
1559
|
await publishSourceEvents(state, recorded);
|
|
1330
1560
|
return recorded;
|
|
@@ -1374,7 +1604,16 @@ function nativeIds(params) {
|
|
|
1374
1604
|
};
|
|
1375
1605
|
}
|
|
1376
1606
|
async function persist(state, scopeKey, operation) {
|
|
1377
|
-
|
|
1607
|
+
const saved = await state.journal.putOperation(scopeKey, operation);
|
|
1608
|
+
await syncParameterAgentOperation(state, saved);
|
|
1609
|
+
return saved;
|
|
1610
|
+
}
|
|
1611
|
+
async function syncParameterAgentOperation(state, operation) {
|
|
1612
|
+
if (operation.kind !== 'session.turn')
|
|
1613
|
+
return;
|
|
1614
|
+
if (operation.status === 'completed' || operation.status === 'failed' || operation.status === 'interrupted' || operation.status === 'uncertain') {
|
|
1615
|
+
await finishParameterAgentTask(state, operation, operation.status, operation.error);
|
|
1616
|
+
}
|
|
1378
1617
|
}
|
|
1379
1618
|
function native(state) {
|
|
1380
1619
|
if (!state.native)
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { readObservedFile, withObservedFile } from '../workspaces/revisions.js';
|
|
2
|
+
import { observeWorkspaceDirectories } from '../workspaces/directory-revisions.js';
|
|
2
3
|
import { registerWorkspace, revisionScope, sessionWorkspaceRoot, workspaceRoot, WorkspaceContextError } from '../workspaces/registry.js';
|
|
3
4
|
import { constants } from 'node:fs';
|
|
4
5
|
import { access as accessDirectory, stat } from 'node:fs/promises';
|
|
@@ -6,9 +7,10 @@ import { workspaceRegistrationRequestSchema, workspaceFileSearchQuerySchema, HTT
|
|
|
6
7
|
import { controlTokenMatches, extractControlToken } from './auth.js';
|
|
7
8
|
import { applyRuntimeEndpointPatch } from './endpoints.js';
|
|
8
9
|
import { wakeSourceEventUploader } from './source-uploader.js';
|
|
9
|
-
import { InvalidWorkspacePathError,
|
|
10
|
+
import { InvalidWorkspacePathError, } from '../workspaces/files.js';
|
|
10
11
|
import { GitWorkspaceError, readWorkspaceGitDiff, readWorkspaceGitFile, readWorkspaceGitGraph, readWorkspaceGitStatus, } from '../workspaces/git.js';
|
|
11
12
|
import { readWorkspaceParameters } from '../workspaces/parameters.js';
|
|
13
|
+
import { listParameterAgentTasks } from '../workspaces/parameter-agent.js';
|
|
12
14
|
import { readDependencies } from '../workspaces/dependencies.js';
|
|
13
15
|
import { desktopHost, desktopRoute } from './desktop-host.js';
|
|
14
16
|
import { ensureCliCredentials } from '../workspaces/cli-credentials.js';
|
|
@@ -40,6 +42,7 @@ import { serveWorkspaceArchive } from '../workspaces/archive.js';
|
|
|
40
42
|
import { handleWorkspaceTransfer } from './workspace-transfer.js';
|
|
41
43
|
import { serveSessionImage } from '../workspaces/session-image.js';
|
|
42
44
|
import { restoreNativeSession, SessionRestoreError } from './session-restore.js';
|
|
45
|
+
import { handleAssetTransferRequest } from './asset-transfers.js';
|
|
43
46
|
export async function handleRuntimeRequest(state, request, response) {
|
|
44
47
|
const url = new URL(request.url ?? '/', 'http://127.0.0.1');
|
|
45
48
|
const directoryName = url.searchParams.get('directoryName') ?? 'basic';
|
|
@@ -53,6 +56,11 @@ export async function handleRuntimeRequest(state, request, response) {
|
|
|
53
56
|
return;
|
|
54
57
|
}
|
|
55
58
|
try {
|
|
59
|
+
const transfer = await handleAssetTransferRequest(state, request, url);
|
|
60
|
+
if (transfer) {
|
|
61
|
+
writeJson(response, transfer.status, transfer.body);
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
56
64
|
const batch = await dispatchBatchRoute(state, request, url);
|
|
57
65
|
if (batch) {
|
|
58
66
|
writeJson(response, batch.status, batch.body);
|
|
@@ -94,6 +102,7 @@ export async function handleRuntimeRequest(state, request, response) {
|
|
|
94
102
|
instanceToken: state.instanceToken,
|
|
95
103
|
permissionsVersion: 1,
|
|
96
104
|
composerContextVersion: 1,
|
|
105
|
+
parameterAgentVersion: 1,
|
|
97
106
|
remixReferencesVersion: 1,
|
|
98
107
|
batchSourceFreezeRevision: 2,
|
|
99
108
|
...(state.native?.workspaceUi ? { workspaceUiVersion: 1 } : {}),
|
|
@@ -505,7 +514,8 @@ export async function handleRuntimeRequest(state, request, response) {
|
|
|
505
514
|
return;
|
|
506
515
|
const workspaceId = url.searchParams.get('workspaceId') ?? undefined;
|
|
507
516
|
const root = await workspaceRoot(state, workspaceId, directoryName);
|
|
508
|
-
const
|
|
517
|
+
const scope = revisionScope(state, workspaceId, directoryName);
|
|
518
|
+
const listed = await state.journal.exclusive(`workspace:${scope ?? 'single'}`, () => observeWorkspaceDirectories(root, state.journal, scope));
|
|
509
519
|
console.log(`[workspace-files] GET /runtime/files workspaceId=${workspaceId ?? '-'} root=${root} files=${listed.files.length}`);
|
|
510
520
|
writeJson(response, 200, listed);
|
|
511
521
|
return;
|
|
@@ -639,6 +649,18 @@ export async function handleRuntimeRequest(state, request, response) {
|
|
|
639
649
|
writeJson(response, 200, await readObservedParameters(state, url.searchParams.get('workspaceId') ?? undefined, directoryName));
|
|
640
650
|
return;
|
|
641
651
|
}
|
|
652
|
+
if (request.method === 'GET' && url.pathname === '/runtime/parameter-tasks') {
|
|
653
|
+
if (writeDestroyed(state, response))
|
|
654
|
+
return;
|
|
655
|
+
if (directoryName === 'root') {
|
|
656
|
+
writeJson(response, 400, { error: 'invalid_workspace_directory' });
|
|
657
|
+
return;
|
|
658
|
+
}
|
|
659
|
+
const workspaceId = url.searchParams.get('workspaceId') ?? undefined;
|
|
660
|
+
const root = await workspaceRoot(state, workspaceId, directoryName);
|
|
661
|
+
writeJson(response, 200, { tasks: await listParameterAgentTasks(state, workspaceId, directoryName, root) });
|
|
662
|
+
return;
|
|
663
|
+
}
|
|
642
664
|
if (request.method === 'GET' && url.pathname === '/runtime/terminals') {
|
|
643
665
|
if (writeDestroyed(state, response))
|
|
644
666
|
return;
|
|
@@ -1105,12 +1127,14 @@ async function handleSessionHistory(state, response, workspaceId, sessionId) {
|
|
|
1105
1127
|
async function readObservedParameters(state, workspaceId, directoryName = 'basic') {
|
|
1106
1128
|
const root = await workspaceRoot(state, workspaceId, directoryName);
|
|
1107
1129
|
const scope = revisionScope(state, workspaceId, directoryName);
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1130
|
+
return state.journal.exclusive(`workspace:${scope ?? 'single'}`, async () => {
|
|
1131
|
+
const first = await readWorkspaceParameters(root, state.journal.fileRevisions(scope));
|
|
1132
|
+
for (const path of [first.schemaPath, first.dataPath]) {
|
|
1133
|
+
if (path)
|
|
1134
|
+
await withObservedFile(state, workspaceId, path, async () => undefined, directoryName);
|
|
1135
|
+
}
|
|
1136
|
+
return readWorkspaceParameters(root, state.journal.fileRevisions(scope));
|
|
1137
|
+
});
|
|
1114
1138
|
}
|
|
1115
1139
|
function writeError(response, error) {
|
|
1116
1140
|
writeJson(response, HTTP_STATUS_BY_ERROR[error.code], error);
|