arco-workbench 0.2.2 → 0.2.5
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/CONTRIBUTING.md +1 -1
- package/THIRD_PARTY_NOTICES +2 -2
- package/client/dist/assets/{PhosphorBackdrop-BbR3xmfD.js → PhosphorBackdrop-CLILIwOQ.js} +1 -1
- package/client/dist/assets/{ThemedBackgroundShaderImpl-UMjbs9ZN.js → ThemedBackgroundShaderImpl-B87chcb5.js} +1 -1
- package/client/dist/assets/{XtermView-n135qz-f.js → XtermView-BP_j7WSN.js} +1 -1
- package/client/dist/assets/{galleryEditor-CFSke4by.js → galleryEditor-B90phoBI.js} +1 -1
- package/client/dist/assets/{index-DeoJbjI3.js → index-BfPp1Oup.js} +270 -270
- package/client/dist/index.html +1 -1
- package/client/dist/manifest-mobile.webmanifest +1 -0
- package/client/src/App.tsx +2 -2
- package/client/src/components/AuthReloginNotice.tsx +7 -6
- package/client/src/components/ChatMessage.tsx +41 -29
- package/client/src/components/ChatPanel.tsx +17 -4
- package/client/src/components/ClaudeNativeAccountPicker.tsx +32 -0
- package/client/src/components/ClaudeNativeAuthRow.tsx +71 -19
- package/client/src/components/ClusterRightPanel/AddWorkerSection.tsx +11 -281
- package/client/src/components/ClusterRightPanel/AutoPickupControl.tsx +1 -1
- package/client/src/components/ClusterRightPanel/FreshMemberForm.tsx +315 -0
- package/client/src/components/ClusterRightPanel/ReplaceMemberDialog.tsx +17 -7
- package/client/src/components/ClusterRightPanel/index.tsx +1 -1
- package/client/src/components/ClusterRightPanel/useFreshMemberPicker.ts +6 -4
- package/client/src/components/ClusterTab.tsx +2 -2
- package/client/src/components/Connections/Connections.tsx +7 -11
- package/client/src/components/Connections/model.ts +3 -1
- package/client/src/components/FileViewerModal.tsx +54 -17
- package/client/src/components/GitHubPanel/index.tsx +9 -5
- package/client/src/components/HandoffDialog.tsx +5 -3
- package/client/src/components/MobileShell.tsx +1 -33
- package/client/src/components/OperatorQuestionNotice.tsx +5 -4
- package/client/src/components/ProvidersPopover.tsx +6 -2
- package/client/src/components/RightPanel/ActivityTab.tsx +2 -1
- package/client/src/components/RightPanel/ConfigTab.tsx +23 -5
- package/client/src/components/RightPanel/OutputsPanel.tsx +21 -9
- package/client/src/components/RightPanel/outputsReconcile.ts +31 -0
- package/client/src/components/SettingsPanel.tsx +7 -10
- package/client/src/components/SpawnDialog.tsx +14 -3
- package/client/src/components/TabBar.tsx +2 -2
- package/client/src/components/TabContextMenu.tsx +73 -133
- package/client/src/components/TerminalInput.tsx +4 -3
- package/client/src/components/TranscriptWorkerDialog.tsx +14 -4
- package/client/src/components/UsageBar.tsx +37 -18
- package/client/src/components/WorkflowCreator/ClusterMembersSection.tsx +29 -3
- package/client/src/components/WorkflowCreator/index.tsx +29 -15
- package/client/src/components/WorkflowView.tsx +1 -1
- package/client/src/components/providerIndicator.ts +7 -3
- package/client/src/components/research/QuickResearchOverview.tsx +7 -3
- package/client/src/components/research/SavedQuickKeep.tsx +7 -3
- package/client/src/components/settings/GitHubAuthRow.tsx +34 -0
- package/client/src/explorer/ArtifactsLens.tsx +17 -8
- package/client/src/explorer/ExplorerApp.tsx +3 -3
- package/client/src/explorer/types.ts +3 -1
- package/client/src/help/content/cluster.tsx +10 -4
- package/client/src/help/content/composer.tsx +3 -2
- package/client/src/help/content/header.tsx +6 -3
- package/client/src/help/content/misc.tsx +9 -7
- package/client/src/help/content/rightPanel.tsx +11 -6
- package/client/src/help/content/settings.tsx +14 -3
- package/client/src/help/content/tabbar.tsx +1 -1
- package/client/src/help/manualSections/actions.tsx +5 -1
- package/client/src/help/manualSections/clusters.tsx +21 -15
- package/client/src/help/manualSections/configuration.tsx +6 -4
- package/client/src/help/manualSections/gettingStarted.tsx +4 -2
- package/client/src/help/manualSections/maintenance.tsx +24 -0
- package/client/src/help/manualSections/powerFeatures.tsx +4 -2
- package/client/src/help/manualSections/providers.tsx +11 -4
- package/client/src/help/manualSections/workspace.tsx +3 -3
- package/client/src/hooks/useClaudeNativeCatalog.ts +26 -0
- package/client/src/hooks/useClaudeNativeLogin.ts +16 -11
- package/client/src/hooks/useWebSocket.ts +4 -2
- package/client/src/layout/layoutRange.ts +14 -5
- package/client/src/main.tsx +2 -0
- package/client/src/questions/waitingQuestion.ts +2 -0
- package/client/src/stores/appStore.ts +5 -1
- package/client/src/stores/appStore.types.ts +2 -0
- package/client/src/stores/replayContext.ts +20 -0
- package/client/src/utils/chatFileLinks.ts +34 -3
- package/client/src/utils/claudeAuth.ts +9 -1
- package/client/src/ws/handleServerMessage.ts +11 -3
- package/docs/ARCHITECTURE.md +3 -3
- package/docs/BACKUP.md +1 -1
- package/docs/CHECKPOINTS.md +67 -3
- package/docs/CLIENT.md +11 -6
- package/docs/EXTENDING.md +1 -1
- package/docs/FEATURES.md +3 -3
- package/docs/GETTING_STARTED.md +5 -4
- package/docs/GIT_WORKBENCH.md +8 -0
- package/docs/GLOSSARY.md +2 -2
- package/docs/GOTCHAS.md +4 -4
- package/docs/HTTP_API.md +63 -30
- package/docs/OPERATIONS.md +11 -0
- package/docs/OPERATOR_ACTIONS.md +2 -2
- package/docs/OUTPUTS.md +48 -6
- package/docs/PERSISTENCE.md +1 -1
- package/docs/PRIMITIVES.md +4 -2
- package/docs/PROTOCOL_CLUSTER.md +12 -6
- package/docs/PROTOCOL_PRIMITIVES.md +1 -1
- package/docs/PROVIDERS.md +47 -10
- package/docs/RESEARCH.md +3 -3
- package/docs/SETTINGS.md +9 -4
- package/node_modules/@arco/shared/dist/protocol/clusters.d.ts +15 -3
- package/node_modules/@arco/shared/dist/protocol/clusters.js +1 -1
- package/node_modules/@arco/shared/dist/protocol/models.d.ts +6 -1
- package/node_modules/@arco/shared/dist/protocol/operatorQuestions.d.ts +2 -1
- package/node_modules/@arco/shared/dist/protocol/settings.d.ts +3 -0
- package/node_modules/@arco/shared/dist/protocol/settings.js +5 -0
- package/node_modules/@arco/shared/dist/protocol/workflows.d.ts +1 -0
- package/node_modules/@arco/shared/dist/protocol/workflows.js +0 -2
- package/node_modules/@arco/shared/package.json +1 -1
- package/package.json +2 -2
- package/scripts/packaging/services.mjs +20 -1
- package/scripts/packaging/update.mjs +37 -2
- package/server/dist/attention.d.ts +6 -0
- package/server/dist/attention.js +6 -0
- package/server/dist/auth.d.ts +5 -0
- package/server/dist/auth.js +31 -20
- package/server/dist/clusterAutoTurn.d.ts +5 -1
- package/server/dist/clusterAutoTurn.js +31 -9
- package/server/dist/clusterPresets.js +3 -3
- package/server/dist/effortValidation.d.ts +2 -2
- package/server/dist/effortValidation.js +4 -4
- package/server/dist/explorerArtifacts.d.ts +1 -0
- package/server/dist/explorerArtifacts.js +12 -1
- package/server/dist/explorerDocs.d.ts +1 -0
- package/server/dist/explorerDocs.js +4 -4
- package/server/dist/geminiMembers.d.ts +7 -1
- package/server/dist/geminiMembers.js +28 -14
- package/server/dist/gitSnapshots.d.ts +1 -0
- package/server/dist/gitSnapshots.js +547 -83
- package/server/dist/http/clusterRoutes.js +9 -3
- package/server/dist/http/conversationFiles.d.ts +36 -0
- package/server/dist/http/conversationFiles.js +222 -0
- package/server/dist/http/fileBytes.d.ts +3 -0
- package/server/dist/http/fileBytes.js +33 -0
- package/server/dist/http/fileContentRoute.d.ts +2 -0
- package/server/dist/http/fileContentRoute.js +139 -0
- package/server/dist/http/fileRead.d.ts +54 -2
- package/server/dist/http/fileRead.js +31 -24
- package/server/dist/http/outputRoutes.js +14 -21
- package/server/dist/http/readConfinement.d.ts +0 -11
- package/server/dist/http/readConfinement.js +4 -30
- package/server/dist/http/router.js +41 -66
- package/server/dist/index.js +26 -12
- package/server/dist/management/initHubLink.js +1 -1
- package/server/dist/outputs.js +8 -0
- package/server/dist/primitives/exportContext.d.ts +2 -0
- package/server/dist/primitives/exportContext.js +13 -2
- package/server/dist/primitives/runCompare.d.ts +7 -1
- package/server/dist/primitives/runCompare.js +44 -20
- package/server/dist/project/taskLedger.js +46 -34
- package/server/dist/providerAccounts.d.ts +4 -0
- package/server/dist/providerAccounts.js +20 -1
- package/server/dist/providers/antigravity/artifacts.d.ts +23 -0
- package/server/dist/providers/antigravity/artifacts.js +140 -0
- package/server/dist/providers/antigravity/index.js +85 -7
- package/server/dist/providers/antigravity/questions.d.ts +2 -0
- package/server/dist/providers/antigravity/questions.js +58 -0
- package/server/dist/providers/claude-native/auth.d.ts +9 -8
- package/server/dist/providers/claude-native/auth.js +50 -58
- package/server/dist/providers/claude-native/authStatus.d.ts +2 -2
- package/server/dist/providers/claude-native/authStatus.js +9 -7
- package/server/dist/providers/claude-native/catalog.d.ts +6 -5
- package/server/dist/providers/claude-native/catalog.js +50 -39
- package/server/dist/providers/claude-native/oauth.d.ts +10 -9
- package/server/dist/providers/claude-native/oauth.js +120 -96
- package/server/dist/providers/claude-native/worker.d.ts +1 -0
- package/server/dist/providers/claude-native/worker.js +38 -23
- package/server/dist/providers/codex-appserver/operatorQuestions.d.ts +5 -3
- package/server/dist/providers/codex-appserver/operatorQuestions.js +27 -13
- package/server/dist/providers/codexChatBoundary.js +6 -1
- package/server/dist/research/quickPromotion.d.ts +3 -0
- package/server/dist/research/quickPromotion.js +26 -9
- package/server/dist/research/savedQuickPromotion.js +2 -11
- package/server/dist/server/broadcast.js +6 -0
- package/server/dist/settings.d.ts +1 -0
- package/server/dist/settings.js +39 -7
- package/server/dist/skills.js +1 -1
- package/server/dist/smartPickupAdapters.d.ts +1 -0
- package/server/dist/smartPickupAdapters.js +2 -2
- package/server/dist/smartPickupObserver.js +8 -5
- package/server/dist/thirdPartySkills.js +11 -5
- package/server/dist/turnChanges.d.ts +1 -1
- package/server/dist/turnChanges.js +5 -4
- package/server/dist/usage.d.ts +1 -1
- package/server/dist/usage.js +39 -27
- package/server/dist/workers/WorkerManager.d.ts +1 -0
- package/server/dist/workers/WorkerManager.js +1 -0
- package/server/dist/workers/processKill.js +37 -24
- package/server/dist/workflowMeta.js +2 -2
- package/server/dist/ws/clusterHandlers.d.ts +2 -2
- package/server/dist/ws/clusterHandlers.js +127 -113
- package/server/dist/ws/clusterMembers.d.ts +1 -1
- package/server/dist/ws/clusterMembers.js +34 -4
- package/server/dist/ws/compactHandlers.js +30 -14
- package/server/dist/ws/compareHandlers.js +53 -21
- package/server/dist/ws/gateHandlers.js +2 -0
- package/server/dist/ws/genesisHandlers.js +5 -3
- package/server/dist/ws/handoffHandlers.d.ts +1 -1
- package/server/dist/ws/handoffHandlers.js +115 -39
- package/server/dist/ws/transcriptWorkerHandlers.js +7 -2
- package/server/dist/ws/turnEngine.js +37 -19
- package/server/dist/ws/updatePrimaryConfig.d.ts +3 -2
- package/server/dist/ws/updatePrimaryConfig.js +236 -133
- package/server/dist/ws/workflowHandlers.js +21 -4
- package/server/package.json +1 -1
- package/server/src/attention.ts +7 -0
- package/server/src/auth.ts +33 -20
- package/server/src/clusterAutoTurn.ts +31 -11
- package/server/src/clusterPresets.ts +2 -2
- package/server/src/effortValidation.ts +4 -4
- package/server/src/explorerArtifacts.ts +12 -1
- package/server/src/explorerDocs.ts +5 -5
- package/server/src/geminiMembers.ts +26 -15
- package/server/src/gitSnapshots.ts +538 -82
- package/server/src/http/clusterRoutes.ts +10 -3
- package/server/src/http/conversationFiles.ts +231 -0
- package/server/src/http/fileBytes.ts +34 -0
- package/server/src/http/fileContentRoute.ts +123 -0
- package/server/src/http/fileRead.ts +30 -25
- package/server/src/http/outputRoutes.ts +13 -13
- package/server/src/http/readConfinement.ts +3 -30
- package/server/src/http/router.ts +39 -62
- package/server/src/index.ts +27 -18
- package/server/src/management/initHubLink.ts +1 -1
- package/server/src/outputs.ts +8 -0
- package/server/src/primitives/exportContext.ts +14 -2
- package/server/src/primitives/runCompare.ts +73 -46
- package/server/src/project/taskLedger.ts +47 -30
- package/server/src/providerAccounts.ts +20 -1
- package/server/src/providers/antigravity/artifacts.ts +121 -0
- package/server/src/providers/antigravity/index.ts +64 -6
- package/server/src/providers/antigravity/questions.ts +52 -0
- package/server/src/providers/claude-native/auth.ts +45 -60
- package/server/src/providers/claude-native/authStatus.ts +9 -8
- package/server/src/providers/claude-native/catalog.ts +52 -35
- package/server/src/providers/claude-native/oauth.ts +101 -77
- package/server/src/providers/claude-native/worker.ts +38 -22
- package/server/src/providers/codex-appserver/operatorQuestions.ts +26 -12
- package/server/src/providers/codexChatBoundary.ts +6 -1
- package/server/src/research/quickPromotion.ts +24 -6
- package/server/src/research/savedQuickPromotion.ts +2 -8
- package/server/src/server/broadcast.ts +4 -0
- package/server/src/settings.ts +36 -8
- package/server/src/skills.ts +1 -1
- package/server/src/smartPickupAdapters.ts +3 -2
- package/server/src/smartPickupObserver.ts +8 -5
- package/server/src/thirdPartySkills.ts +11 -5
- package/server/src/turnChanges.ts +5 -4
- package/server/src/usage.ts +30 -22
- package/server/src/workers/WorkerManager.ts +2 -0
- package/server/src/workers/processKill.ts +37 -23
- package/server/src/workflowMeta.ts +2 -2
- package/server/src/ws/clusterHandlers.ts +107 -104
- package/server/src/ws/clusterMembers.ts +25 -6
- package/server/src/ws/compactHandlers.ts +29 -15
- package/server/src/ws/compareHandlers.ts +59 -25
- package/server/src/ws/gateHandlers.ts +2 -0
- package/server/src/ws/genesisHandlers.ts +5 -4
- package/server/src/ws/handoffHandlers.ts +105 -37
- package/server/src/ws/transcriptWorkerHandlers.ts +6 -2
- package/server/src/ws/turnEngine.ts +36 -18
- package/server/src/ws/updatePrimaryConfig.ts +230 -132
- package/server/src/ws/workflowHandlers.ts +20 -4
- package/shared/dist/protocol/clusters.d.ts +15 -3
- package/shared/dist/protocol/clusters.js +1 -1
- package/shared/dist/protocol/models.d.ts +6 -1
- package/shared/dist/protocol/operatorQuestions.d.ts +2 -1
- package/shared/dist/protocol/settings.d.ts +3 -0
- package/shared/dist/protocol/settings.js +5 -0
- package/shared/dist/protocol/workflows.d.ts +1 -0
- package/shared/dist/protocol/workflows.js +0 -2
- package/shared/src/protocol/clusters.ts +23 -5
- package/shared/src/protocol/compare.ts +2 -2
- package/shared/src/protocol/models.ts +8 -4
- package/shared/src/protocol/operatorQuestions.ts +2 -1
- package/shared/src/protocol/settings.ts +8 -1
- package/shared/src/protocol/workflows.ts +1 -1
|
@@ -24,7 +24,12 @@ export function supportsCodexChat(probe: ChatCapabilityProbe, web = false): bool
|
|
|
24
24
|
let validated = false;
|
|
25
25
|
try { const startup = JSON.parse(probe.startupConfig ?? ''); validated = typeof startup.appServerVersion === 'string' && !startup.error; } catch { /* Unsupported or failed strict configuration probe. */ }
|
|
26
26
|
return supportedVersion && validated && (!web || listed(probe.listedFeatures ?? '', 'code_mode_host')) && requiredFeatures.every(name => listed(probe.listedFeatures ?? '', name))
|
|
27
|
-
&& disabledFeatures.filter(name => requiredFeatures.includes(name) || listed(probe.listedFeatures ?? '', name)).every(name =>
|
|
27
|
+
&& disabledFeatures.filter(name => requiredFeatures.includes(name) || listed(probe.listedFeatures ?? '', name)).every(name => {
|
|
28
|
+
const enabled = web && name === 'code_mode_host';
|
|
29
|
+
const activeStages = 'stable|experimental|under development';
|
|
30
|
+
const stages = requiredFeatures.includes(name) || enabled ? activeStages : `${activeStages}|deprecated|removed`;
|
|
31
|
+
return new RegExp(`^${name}\\s+(?:${stages})\\s+${enabled}\\s*$`, 'm').test(probe.features ?? '');
|
|
32
|
+
})
|
|
28
33
|
&& [probe.execHelp, probe.resumeHelp].every(help => help?.includes('--ignore-user-config') && help.includes('--ignore-rules') && help.includes('--strict-config'));
|
|
29
34
|
}
|
|
30
35
|
const cache = new Map<string, { expires: number; supported: boolean; overrides: readonly string[] }>();
|
|
@@ -77,6 +77,29 @@ function schedule(clusterId: string): void {
|
|
|
77
77
|
timer.unref(); timers.set(clusterId, timer);
|
|
78
78
|
}
|
|
79
79
|
|
|
80
|
+
export class QuickPromotionFolderMissingError extends Error {}
|
|
81
|
+
|
|
82
|
+
export async function resolveQuickPromotionRoot(source: string, folderRoot?: string): Promise<string> {
|
|
83
|
+
const settings = await readSettings();
|
|
84
|
+
const selected = folderRoot?.trim();
|
|
85
|
+
const requested = selected || settings.researchFolder;
|
|
86
|
+
if (!requested || !isAbsolute(requested)) throw new Error('Choose a research folder.');
|
|
87
|
+
|
|
88
|
+
let root: string;
|
|
89
|
+
try {
|
|
90
|
+
root = safeDirectory(requested);
|
|
91
|
+
} catch (error) {
|
|
92
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
|
|
93
|
+
throw new QuickPromotionFolderMissingError(selected
|
|
94
|
+
? 'The folder you chose is gone. Choose another folder.'
|
|
95
|
+
: 'The saved research folder is gone. Choose a new folder to keep this research.');
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
if (isPathWithin(source, root) || isPathWithin(root, source)) throw new Error('Choose a research folder outside the Quick research workspace.');
|
|
99
|
+
if (selected && root !== settings.researchFolder) await patchSettings({ researchFolder: root });
|
|
100
|
+
return root;
|
|
101
|
+
}
|
|
102
|
+
|
|
80
103
|
export async function requestQuickPromotion(clusterId: string, folderRoot?: string): Promise<QuickPromotionJournal> {
|
|
81
104
|
return withFileLock(journalPath(clusterId), async () => {
|
|
82
105
|
const current = await readQuickPromotion(clusterId);
|
|
@@ -84,12 +107,7 @@ export async function requestQuickPromotion(clusterId: string, folderRoot?: stri
|
|
|
84
107
|
const state = await loadResearch(clusterId);
|
|
85
108
|
if (!state?.quick || state.closedAt) throw new Error('This is not an open Quick research.');
|
|
86
109
|
if (!/^[0-9a-f-]{36}$/i.test(state.projectId) || resolve(state.folder) !== resolve(join(await fs.realpath(arcoHome()), 'chat-workspaces', state.projectId)) || (await fs.lstat(state.folder)).isSymbolicLink()) throw new Error('The Quick research workspace is unavailable.');
|
|
87
|
-
const
|
|
88
|
-
const requested = settings.researchFolder || folderRoot?.trim();
|
|
89
|
-
if (!requested || !isAbsolute(requested)) throw new Error('Choose a research folder.');
|
|
90
|
-
const root = safeDirectory(requested);
|
|
91
|
-
if (isPathWithin(state.folder, root) || isPathWithin(root, state.folder)) throw new Error('Choose a research folder outside the Quick research workspace.');
|
|
92
|
-
if (!settings.researchFolder) await patchSettings({ researchFolder: root });
|
|
110
|
+
const root = await resolveQuickPromotionRoot(state.folder, folderRoot);
|
|
93
111
|
const journal: QuickPromotionJournal = { clusterId, projectId: state.projectId, directorWorkflowId: state.directorWorkflowId, source: state.folder, root, phase: 'waiting' };
|
|
94
112
|
await save(journal); schedule(clusterId); return journal;
|
|
95
113
|
});
|
|
@@ -6,13 +6,12 @@ import { arcoHome } from '../arcoHome.js';
|
|
|
6
6
|
import { antigravityChatWorkspace, chatStorageDir } from '../chatMode.js';
|
|
7
7
|
import { readLogLines } from '../eventLog.js';
|
|
8
8
|
import { isPathWithin, safeDirectory } from '../fileAccessPolicy.js';
|
|
9
|
-
import { readSettings, patchSettings } from '../settings.js';
|
|
10
9
|
import { workflows } from '../server/state.js';
|
|
11
10
|
import { flushWorkflowBuffer } from '../workflowStore.js';
|
|
12
11
|
import { createResearchFolder, writeProjectFiles } from './researchFolder.js';
|
|
13
12
|
import { closedResearchRecordPath } from './researchClose.js';
|
|
14
13
|
import { addToLibrary, readClosedRecord } from './researchLibrary.js';
|
|
15
|
-
import { beginQuickPromotion, copyWorkspace, finishQuickPromotion, yieldQuickPromotionToMessage, type ActivePromotion } from './quickPromotion.js';
|
|
14
|
+
import { beginQuickPromotion, copyWorkspace, finishQuickPromotion, resolveQuickPromotionRoot, yieldQuickPromotionToMessage, type ActivePromotion } from './quickPromotion.js';
|
|
16
15
|
|
|
17
16
|
interface Journal { projectId: string; source: string; root: string; target?: string; phase: 'waiting' | 'copying' | 'switching' | 'done' | 'error'; message?: string }
|
|
18
17
|
const validId = (id: string) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id);
|
|
@@ -57,12 +56,7 @@ export async function requestSavedQuickPromotion(id: string, folderRoot?: string
|
|
|
57
56
|
const state = await savedRecord(id);
|
|
58
57
|
const source = antigravityChatWorkspace(id);
|
|
59
58
|
if (!state?.quick || !state.closedAt || resolve(state.folder) !== resolve(source) || (await fs.lstat(source)).isSymbolicLink()) throw new Error('This saved Chat has no Quick research to keep.');
|
|
60
|
-
const
|
|
61
|
-
const chosen = settings.researchFolder || folderRoot?.trim();
|
|
62
|
-
if (!chosen || !isAbsolute(chosen)) throw new Error('Choose a research folder.');
|
|
63
|
-
const root = safeDirectory(chosen);
|
|
64
|
-
if (isPathWithin(source, root) || isPathWithin(root, source)) throw new Error('Choose a research folder outside the Quick research workspace.');
|
|
65
|
-
if (!settings.researchFolder) await patchSettings({ researchFolder: root });
|
|
59
|
+
const root = await resolveQuickPromotionRoot(source, folderRoot);
|
|
66
60
|
const journal: Journal = { projectId: id, source, root, phase: 'waiting' };
|
|
67
61
|
await save(journal); schedule(id); return journal;
|
|
68
62
|
});
|
|
@@ -444,6 +444,10 @@ function observeTurnBoundary(workflowId: string, wf: WorkflowState, message: Ser
|
|
|
444
444
|
// attention.ts sees every message (questions, gates and errors too) and
|
|
445
445
|
// ignores a repeated start or end itself.
|
|
446
446
|
attention.observeAttention(workflowId, message, { name: wf.config.name ?? '', incognito: !!wf.config.incognito });
|
|
447
|
+
// A finished handoff or fold leaves a smaller conversation in the same member: automatic pickup may resume.
|
|
448
|
+
if (message.type === 'handoff_complete' || message.type === 'context_folded') clusterAutoTurn.noteTurnOutcome(workflowId, null);
|
|
449
|
+
// A terminal request_too_large stops automatic pickup for this member before its turn-end sweep.
|
|
450
|
+
if (message.type === 'error' && typeof message.message === 'string' && clusterAutoTurn.isOversizeError(message.message)) clusterAutoTurn.noteTurnOutcome(workflowId, message.message);
|
|
447
451
|
if (message.type === 'primary_turn_started') {
|
|
448
452
|
if (turnBoundaryState.get(workflowId) === 'open') return;
|
|
449
453
|
turnBoundaryState.set(workflowId, 'open');
|
package/server/src/settings.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
1
2
|
import { sanitizeNativeSubagents } from '@arco/shared';
|
|
2
3
|
import { scanBeforeDeadline } from './scanDeadline.js';
|
|
3
4
|
import { parsePreviewPorts } from './previewProxy.js';
|
|
@@ -24,7 +25,7 @@ import { mkdirSync, realpathSync, watch as fsWatch, type FSWatcher } from 'fs';
|
|
|
24
25
|
import path from 'path';
|
|
25
26
|
import { homedir } from 'os';
|
|
26
27
|
import type { ArcoSettings, ProviderName, ModelName, WorkflowDefaults, EffortLevel, ProviderAccountsConfig, ProviderAccountProfile, FallbackChainsConfig, FallbackLegConfig, PinnedService, OllamaBackendConfig, OllamaUtilityConfig, OllamaCompactionConfig } from '@arco/shared';
|
|
27
|
-
import { VALID_THEME_IDS, VALID_FONT_PACK_IDS, normalizeLegacyThemeId, DEFAULT_UI_SCALE, normalizeUiScale } from '@arco/shared';
|
|
28
|
+
import { isClaudeNativeProfileId, VALID_THEME_IDS, VALID_FONT_PACK_IDS, normalizeLegacyThemeId, DEFAULT_UI_SCALE, normalizeUiScale } from '@arco/shared';
|
|
28
29
|
import { describeConfigValue } from './configValue.js';
|
|
29
30
|
import { atomicWriteFile, withFileLock } from './atomicFile.js';
|
|
30
31
|
import { arcoHome } from './arcoHome.js';
|
|
@@ -283,11 +284,11 @@ function sanitizeAccountBrowser(raw: unknown): ProviderAccountProfile['authBrows
|
|
|
283
284
|
return args && args.length > 0 ? { command, args } : { command };
|
|
284
285
|
}
|
|
285
286
|
|
|
286
|
-
function sanitizeAccountProfile(raw: unknown, provider:
|
|
287
|
+
function sanitizeAccountProfile(raw: unknown, provider: keyof ProviderAccountsConfig): ProviderAccountProfile | null {
|
|
287
288
|
if (!raw || typeof raw !== 'object') return null;
|
|
288
289
|
const r = raw as Record<string, unknown>;
|
|
289
290
|
const id = typeof r.id === 'string' ? r.id.trim() : '';
|
|
290
|
-
if (!ACCOUNT_ID_PATTERN.test(id)) return null;
|
|
291
|
+
if (provider === 'claudeNative' ? !isClaudeNativeProfileId(id) : !ACCOUNT_ID_PATTERN.test(id)) return null;
|
|
291
292
|
const labelRaw = typeof r.label === 'string' ? r.label.trim().replace(/[\r\n\t]+/g, ' ') : id;
|
|
292
293
|
const label = (labelRaw || id).slice(0, 32);
|
|
293
294
|
const shortRaw = typeof r.shortLabel === 'string' ? r.shortLabel.trim().replace(/[\r\n\t]+/g, ' ') : '';
|
|
@@ -300,7 +301,7 @@ function sanitizeAccountProfile(raw: unknown, provider: 'codex' | 'claude'): Pro
|
|
|
300
301
|
const codexHome = r.codexHome.trim();
|
|
301
302
|
if (codexHome && codexHome.length <= 512 && !/[\r\n]/.test(codexHome)) out.codexHome = codexHome;
|
|
302
303
|
}
|
|
303
|
-
const authBrowser = sanitizeAccountBrowser(r.authBrowser);
|
|
304
|
+
const authBrowser = provider === 'claudeNative' ? undefined : sanitizeAccountBrowser(r.authBrowser);
|
|
304
305
|
if (authBrowser) out.authBrowser = authBrowser;
|
|
305
306
|
return out;
|
|
306
307
|
}
|
|
@@ -309,7 +310,7 @@ function sanitizeProviderAccounts(raw: unknown): ProviderAccountsConfig | undefi
|
|
|
309
310
|
if (!raw || typeof raw !== 'object') return undefined;
|
|
310
311
|
const r = raw as Record<string, unknown>;
|
|
311
312
|
const out: ProviderAccountsConfig = {};
|
|
312
|
-
for (const provider of ['codex', 'claude'] as const) {
|
|
313
|
+
for (const provider of ['codex', 'claude', 'claudeNative'] as const) {
|
|
313
314
|
const arr = r[provider];
|
|
314
315
|
if (!Array.isArray(arr)) continue;
|
|
315
316
|
const seen = new Set<string>();
|
|
@@ -802,8 +803,19 @@ export async function readSettings(
|
|
|
802
803
|
// global scope only, so this never recurses.
|
|
803
804
|
if (opts?.includeProject === false) return mergeWithDefaults(global);
|
|
804
805
|
const project = await readJsonFile(projectSettingsPath(cwd), 'project');
|
|
805
|
-
const merged = deepMerge(global, project);
|
|
806
|
-
|
|
806
|
+
const merged = mergeWithDefaults(deepMerge(global, project));
|
|
807
|
+
// A project can tune its transport. The Native profile names and IDs are
|
|
808
|
+
// global operator settings because the same IDs select paid credentials.
|
|
809
|
+
const operatorAccounts = sanitizeProviderAccounts(global.providerAccounts);
|
|
810
|
+
if (merged.providerAccounts || operatorAccounts) {
|
|
811
|
+
const accounts = { ...merged.providerAccounts };
|
|
812
|
+
delete accounts.claude;
|
|
813
|
+
delete accounts.claudeNative;
|
|
814
|
+
if (operatorAccounts?.claude) accounts.claude = operatorAccounts.claude;
|
|
815
|
+
if (operatorAccounts?.claudeNative) accounts.claudeNative = operatorAccounts.claudeNative;
|
|
816
|
+
merged.providerAccounts = Object.keys(accounts).length ? accounts : undefined;
|
|
817
|
+
}
|
|
818
|
+
return merged;
|
|
807
819
|
}
|
|
808
820
|
|
|
809
821
|
export async function writeSettings(next: ArcoSettings): Promise<void> {
|
|
@@ -854,7 +866,7 @@ async function patchSettingsUnlocked(patch: Partial<ArcoSettings>): Promise<Arco
|
|
|
854
866
|
merged.localClusterCapacity = current.localClusterCapacity;
|
|
855
867
|
}
|
|
856
868
|
if ('providerAccounts' in patch) {
|
|
857
|
-
const sanitized = sanitizeProviderAccounts(patch.providerAccounts);
|
|
869
|
+
const sanitized = sanitizeProviderAccounts(patch.providerAccounts ? { ...current.providerAccounts, ...patch.providerAccounts } : patch.providerAccounts);
|
|
858
870
|
if (sanitized) merged.providerAccounts = sanitized;
|
|
859
871
|
} else if (current.providerAccounts) {
|
|
860
872
|
merged.providerAccounts = current.providerAccounts;
|
|
@@ -1175,6 +1187,22 @@ export async function patchSettings(patch: Partial<ArcoSettings>): Promise<ArcoS
|
|
|
1175
1187
|
return withFileLock(GLOBAL_SETTINGS_PATH, () => patchSettingsUnlocked(patch));
|
|
1176
1188
|
}
|
|
1177
1189
|
|
|
1190
|
+
export async function saveClaudeNativeProfile(label: string, id?: string): Promise<ArcoSettings> {
|
|
1191
|
+
const cleanLabel = label.trim();
|
|
1192
|
+
if (!cleanLabel || cleanLabel.length > 32 || /[\r\n\t]/.test(cleanLabel)) throw new Error('Enter an account name of 1 to 32 characters.');
|
|
1193
|
+
return withFileLock(GLOBAL_SETTINGS_PATH, async () => {
|
|
1194
|
+
const current = await readSettings();
|
|
1195
|
+
const accounts = current.providerAccounts ?? {};
|
|
1196
|
+
const profiles = accounts.claudeNative ?? [];
|
|
1197
|
+
if (id && !profiles.some(profile => profile.id === id)) throw new Error('Claude Native account unavailable.');
|
|
1198
|
+
if (!id && profiles.length >= 8) throw new Error('Up to 8 additional Claude Native accounts are supported.');
|
|
1199
|
+
const next = id
|
|
1200
|
+
? profiles.map(profile => profile.id === id ? { ...profile, label: cleanLabel } : profile)
|
|
1201
|
+
: [...profiles, { id: `native-${randomBytes(12).toString('hex')}`, label: cleanLabel }];
|
|
1202
|
+
return patchSettingsUnlocked({ providerAccounts: { ...accounts, claudeNative: next } });
|
|
1203
|
+
});
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1178
1206
|
// ── Watchers (HMR) ───────────────────────────────────────────────────────
|
|
1179
1207
|
//
|
|
1180
1208
|
// One global watcher and one per-cwd project watcher. Both watch the parent
|
package/server/src/skills.ts
CHANGED
|
@@ -41,7 +41,7 @@ export interface SkillRef { scope: SkillScope; slug: string }
|
|
|
41
41
|
// from the SKILLS menu; model-invoked entries also appear in the manifest.
|
|
42
42
|
export type PickedSkillScope = SkillScope | 'builtin';
|
|
43
43
|
export interface BuiltinSkillSummary { slug: string; name: string; description: string; scope: 'builtin'; operatorOnly: boolean; off?: boolean; replaced?: boolean; path?: string }
|
|
44
|
-
const OPERATOR_BUILTINS = new Set(['grill-me', 'grill-with-docs', 'wait-what', 'retro']);
|
|
44
|
+
const OPERATOR_BUILTINS = new Set(['grill-me', 'grill-with-docs', 'wait-what', 'retro', 'code-review']);
|
|
45
45
|
export function listBuiltinSkills(): BuiltinSkillSummary[] {
|
|
46
46
|
return [...ARCO_BUILTIN_SKILLS.map(s => ({ slug: s.slug, name: s.name, description: s.description, scope: 'builtin' as const, operatorOnly: s.operatorOnly })), ...THIRD_PARTY_SKILL_FILES.map(({ slug, files }) => {
|
|
47
47
|
const parsed = parseSkillFile(files['SKILL.md']);
|
|
@@ -50,6 +50,7 @@ import { cursorAgentEnv } from './providers/cursor/agentEnv.js';
|
|
|
50
50
|
|
|
51
51
|
export interface EvaluatorRequest {
|
|
52
52
|
model: string;
|
|
53
|
+
providerAccountRef?: string;
|
|
53
54
|
instructions: string;
|
|
54
55
|
prompt: string;
|
|
55
56
|
timeoutMs: number;
|
|
@@ -179,7 +180,7 @@ export function claudeAdapter(opts: { fetchImpl?: typeof fetch; tokens?: () => P
|
|
|
179
180
|
async evaluate(req) {
|
|
180
181
|
const { signal, done } = deadline(req);
|
|
181
182
|
try {
|
|
182
|
-
const { accessToken } = await tokens().catch(() => { throw new EvaluatorRefused('not_signed_in'); });
|
|
183
|
+
const { accessToken } = await tokens(req.providerAccountRef).catch(() => { throw new EvaluatorRefused('not_signed_in'); });
|
|
183
184
|
const client = new Anthropic({
|
|
184
185
|
authToken: accessToken,
|
|
185
186
|
apiKey: null,
|
|
@@ -188,7 +189,7 @@ export function claudeAdapter(opts: { fetchImpl?: typeof fetch; tokens?: () => P
|
|
|
188
189
|
defaultHeaders: { 'anthropic-beta': 'claude-code-20250219,oauth-2025-04-20', 'anthropic-dangerous-direct-browser-access': 'true', 'user-agent': CLAUDE_CLI_USER_AGENT, 'x-app': 'cli' },
|
|
189
190
|
...(opts.fetchImpl ? { fetch: opts.fetchImpl } : {}),
|
|
190
191
|
} as ConstructorParameters<typeof Anthropic>[0]);
|
|
191
|
-
const model = resolveClaudeAliasFromCatalog(req.model);
|
|
192
|
+
const model = resolveClaudeAliasFromCatalog(req.model, req.providerAccountRef);
|
|
192
193
|
const resp = await client.messages.create({
|
|
193
194
|
model,
|
|
194
195
|
...shortTextRequestParams(model, req.maxOutputTokens),
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { workflows } from './server/state.js';
|
|
1
2
|
// Smart AUTO-PICKUP observer: decides, for one idle member at a time, what
|
|
2
3
|
// the chosen evaluator proposes for its waiting mail, and records it. In
|
|
3
4
|
// Observe-only mode that record is the whole effect. In Automatic mode a wake
|
|
@@ -25,7 +26,7 @@ import { withFileLock } from './atomicFile.js';
|
|
|
25
26
|
import { buildClusterAutoPickup } from '@arco/shared';
|
|
26
27
|
import { evaluatorAdapter, isStartupFailure } from './smartPickupAdapters.js';
|
|
27
28
|
import { recentSentTo } from './smartPickupThread.js';
|
|
28
|
-
import { isGeminiMember } from './geminiMembers.js';
|
|
29
|
+
import { geminiPickupAllowed, isGeminiMember } from './geminiMembers.js';
|
|
29
30
|
|
|
30
31
|
export interface ObservedDecision {
|
|
31
32
|
clusterId: string;
|
|
@@ -203,9 +204,7 @@ export async function evaluateOnce(clusterId: string, workflowId: string): Promi
|
|
|
203
204
|
const deferLapsed = prior.action === 'defer' && prior.deferUntil !== undefined && deps.now() >= prior.deferUntil;
|
|
204
205
|
if (!deferLapsed && !prior.retryEvaluation) return null;
|
|
205
206
|
}
|
|
206
|
-
|
|
207
|
-
// NUDGE; Smart pickup neither evaluates nor wakes it.
|
|
208
|
-
if (isGeminiMember(workflowId)) {
|
|
207
|
+
if (isGeminiMember(workflowId) && !geminiPickupAllowed(workflowId)) {
|
|
209
208
|
const d = { ...base, action: null, reason: 'operator_send_only', outcome: 'skipped' };
|
|
210
209
|
await record(d);
|
|
211
210
|
return d;
|
|
@@ -244,7 +243,11 @@ export async function evaluateOnce(clusterId: string, workflowId: string): Promi
|
|
|
244
243
|
return null;
|
|
245
244
|
}
|
|
246
245
|
try {
|
|
246
|
+
const recipient = workflows.get(workflowId);
|
|
247
|
+
const providerAccountRef = evaluator.provider === 'claude' && recipient?.primary.provider === 'claude'
|
|
248
|
+
&& recipient.config.claudeTransport !== 'cli' && !recipient.config.ultracode ? recipient.config.providerAccountRef : undefined;
|
|
247
249
|
raw = await evaluatorAdapter(evaluator.provider).evaluate({
|
|
250
|
+
providerAccountRef,
|
|
248
251
|
model: evaluator.model,
|
|
249
252
|
instructions: EVALUATOR_INSTRUCTIONS,
|
|
250
253
|
prompt: evaluatorUserPrompt(snapshot.payload!),
|
|
@@ -301,7 +304,7 @@ export async function evaluateOnce(clusterId: string, workflowId: string): Promi
|
|
|
301
304
|
}
|
|
302
305
|
|
|
303
306
|
// Conditions that pass with time; a wake blocked by one stays owed.
|
|
304
|
-
const TRANSIENT = new Set(['busy', 'cooldown', 'rate_capped', 'limit_wakes_member_hour']);
|
|
307
|
+
const TRANSIENT = new Set(['busy', 'cooldown', 'rate_capped', 'limit_wakes_member_hour', 'member_blocked']);
|
|
305
308
|
|
|
306
309
|
async function gateAndRecord(proposal: ObservedDecision, arm: { sessionId: string; mode: 'smart-observe' | 'smart-auto' }): Promise<ObservedDecision> {
|
|
307
310
|
const result = await gateWake(proposal, arm);
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Source: https://github.com/mattpocock/skills at
|
|
1
|
+
// Source: https://github.com/mattpocock/skills at fe3b143d813e0d9f0b22531e4e4c5f239745d643. MIT; see THIRD_PARTY_NOTICES.
|
|
2
2
|
export const THIRD_PARTY_SKILL_FILES: Array<{ slug: string; files: Record<string, string> }> = [
|
|
3
3
|
{
|
|
4
4
|
"slug": "grill-me",
|
|
@@ -24,6 +24,12 @@ export const THIRD_PARTY_SKILL_FILES: Array<{ slug: string; files: Record<string
|
|
|
24
24
|
"SKILL.md": "---\nname: retro\ndescription: \"Conduct a retrospective on a coding session.\"\ndisable-model-invocation: true\n---\n\nThe user has asked for a **retrospective**. You are suggesting improvements to the coding agent's **environment** to improve future runs.\n\n## Steps\n\n1. Read the `writing-for-agents` skill listed in the skill manifest for the writing style guide.\n\n2. Read the primary sources for the session the user specifies. This may mean searching through session logs on this machine. If the user doesn't specify a session, default to the current one.\n\n3. Look for candidates for improvement in these categories.\n\n- **Navigation**: how easy was it for the agent to find the right files? Are there hidden dependencies between files? Would a **navigation pointer** make it easier? _Use when_ the session took a long time to find a piece of information.\n- **Automated checks**: are there automated checks that could catch errors the agent made? Linting, typing, tests, filesystem linters? Read the repo's own check command first (its `package.json`/build-tool `lint`/`check` scripts, its CI workflow), so a check that already exists but sits unwired or silently broken is the finding, not a reinvention. A repo with no **guardrail** (no pre-commit hook and no CI job running its lint/typecheck/test command) is itself a finding: an un-linted repo is a standing missed opportunity, not a neutral default. _Use when_ the agent made a mistake an automated check could have caught, or the repo has no guardrail at all.\n- **Coding standards**: should the **reviewer agent** be given a new rule to enforce? Should an existing rule be removed or clarified? Classify the violation first: a **mechanical** one (a fixed syntactic pattern, a banned API, an import shape, a file-location rule) gets a deterministic check, full stop: a custom rule in the repo's own linter, a new pre-commit hook, or a new CI job, whichever the repo's language and existing guardrail make cheapest. Default to building the check over writing the rule. Reserve `CODING_STANDARDS.md` for genuine **judgement calls** (cross-file consistency, \"matches the surrounding style,\" anything no guardrail could ever substitute for). _Use when_ the reviewer agent failed to catch a mistake.\n- **Global AGENTS.md**: are there any steering instructions that should be moved to coding standards (or automated checks) instead? _Use when_ the AGENTS.md file is particularly large - in the repo OR the user's global scope.\n- **Tool economy**: did the agent make expensive tool calls that could be streamlined? Is there any custom tooling (CLI's, MCP's) that is particularly token-inefficient? _Use when_ the agent made an expensive tool call.\n- **No-ops**: look for instructions in steering files that don't modify the agent's behavior. _Use when_ the steering files are large and unwieldy.\n- **Information access**: look for opportunities to increase the agent's access to information. Teeing dev server logs, readonly access to third-party services. _Use when_ a crucial piece of information was not available to the agent.\n\n4. Present these candidates to the user, in order of severity.\n\n## Reference\n\n### Implementation vs Review\n\nRemember that all work goes through two stages: implementation and review. The implementation agent has the most **context pressure**. They are responsible for exploration, writing code, and debugging failures.\n\nThe review agent has the least context pressure - it receives a diff, so no exploration needed. It often does not need to write code or debug.\n\nThis means that the review agent should be responsible for imposing coding standards, not the implementation agent.\n\n### Files\n\nYou have access to several files in the repo:\n\n- `CLAUDE.md`/`AGENTS.md`: these files are pushed to the context window of any agent working in this repo. They should be used incredibly sparingly, usually only for **navigation pointers** to other files.\n- `CODING_STANDARDS.md`: this file is read during review, not implementation. Add **navigation pointers** to docs folders if the standards file gets more than 1,000 lines long.\n- Docs: use docs as references files, pointed to by other files. Look for existing docs before writing new ones.\n- Skills: use skills for docs (since their description goes into the agent's context window), or for user-invoked commands. Follow the advice in the `writing-for-agents` skill.\n\n\nSource: mattpocock/skills (MIT); see THIRD_PARTY_NOTICES.\n"
|
|
25
25
|
}
|
|
26
26
|
},
|
|
27
|
+
{
|
|
28
|
+
"slug": "code-review",
|
|
29
|
+
"files": {
|
|
30
|
+
"SKILL.md": "---\nname: code-review\ndescription: Review a specific change against its spec and project standards.\ndisable-model-invocation: true\n---\n\n# Code review\n\nReview the requested change on two axes: standards and spec. This review is read-only: inspect files and history and report findings. Do not modify files, commit, land, publish, or create issues or pull requests. Follow the project's role and delegation rules; the Director retains landing. A single reviewer can perform both axes.\n\n1. Establish the change. Use the supplied or established Git base and diff, including uncommitted changes if requested. Resolve the base and inspect the complete diff and relevant surrounding code. If the base is ambiguous, ask for it. Report an empty or unavailable diff instead of inventing a review.\n2. Establish the spec. Read the relevant Arco board task and linked plan references when available. Otherwise use the supplied spec and project instructions. If no spec is available, say so and report the spec review as incomplete.\n3. Establish the standards. Read applicable project instructions and contribution or coding standards. Consider design smells as judgement calls, not automatic defects; project rules take precedence.\n4. Review the full change against both axes. Trace affected behavior and checks far enough to identify concrete faults, missing requirements and relevant project-rule violations. Do not claim an unrun check or an inferred behavior was observed.\n5. Report actionable findings with severity, file and line, supporting rule or requirement, and the user impact. Separate Standards and Spec findings. State missing evidence and unverified claims; if an axis has no findings, say so and note its coverage limits. Keep architecture-review for broader structural exploration.\n\nSource: mattpocock/skills (MIT), adapted for Arco; see THIRD_PARTY_NOTICES.\n"
|
|
31
|
+
}
|
|
32
|
+
},
|
|
27
33
|
{
|
|
28
34
|
"slug": "grilling",
|
|
29
35
|
"files": {
|
|
@@ -33,9 +39,9 @@ export const THIRD_PARTY_SKILL_FILES: Array<{ slug: string; files: Record<string
|
|
|
33
39
|
{
|
|
34
40
|
"slug": "domain-modeling",
|
|
35
41
|
"files": {
|
|
36
|
-
"SKILL.md": "---\nname: domain-modeling\ndescription: Build and sharpen a project's domain model. Use when discussing codebase terminology, writing or editing a GLOSSARY.md, or recording or editing an ADR.\n---\n\n# Domain Modeling\n\nActively build and sharpen the project's domain model as you design. This is the *active* discipline: challenging terms, inventing edge-case scenarios, and writing the glossary and decisions down the moment they crystallise. (Merely *reading* `GLOSSARY.md` for vocabulary is not this skill: that's a one-line habit any skill can do. This skill is for when you're changing the model, not just consuming it.)\n\n## File structure\n\nMost repos have a single context:\n\n```\n/\n
|
|
37
|
-
"GLOSSARY-FORMAT.md": "# GLOSSARY.md Format\n\n## Structure\n\n```md\n# {Context Name}\n\n{One or two sentence description of what this context is and why it exists.}\n\n## Language\n\n**Order**:\n{A one or two sentence description of the term}\n_Avoid_: Purchase, transaction\n\n**Invoice**:\nA request for payment sent to
|
|
38
|
-
"ADR-FORMAT.md": "# ADR Format\n\nADRs live in `docs/adr/` and use sequential numbering: `0001-slug.md`, `0002-slug.md`, etc.\n\nCreate the `docs/adr/` directory lazily: only when the first ADR is needed.\n\n## Template\n\n```md\n# {Short title of the decision}\n\n{1-3 sentences: what's the context, what did we decide, and why.}\n```\n\nThat's it. An ADR can be a single paragraph. The value is in recording *that* a decision was made and *why*, not in filling out sections.\n\n## Optional sections\n\nOnly include these when they add genuine value. Most ADRs won't need them.\n\n- **Status** frontmatter (`proposed | accepted | deprecated | superseded by ADR-NNNN`): useful when decisions are revisited\n- **Considered Options**: only when the rejected alternatives are worth remembering\n- **Consequences**: only when non-obvious downstream effects need to be called out\n\n## Numbering\n\nScan `docs/adr/` for the highest existing number and increment by one.\n\n## When to offer an ADR\n\nAll three of these must be true:\n\n1. **Hard to reverse**: the cost of changing your mind later is meaningful\n2. **Surprising without context**: a future reader will look at the code and wonder \"why on earth did they do it this way?\"\n3. **The result of a real trade-off**: there were genuine alternatives and you picked one for specific reasons\n\nIf a decision is easy to reverse, skip it: you'll just reverse it. If it's not surprising, nobody will wonder why. If there was no real alternative, there's nothing to record beyond \"we did the obvious thing.\"\n\n### What qualifies\n\n- **Architectural shape.** \"We're using a monorepo.\" \"The write model is event-sourced, the read model is projected into Postgres.\"\n- **Integration patterns between contexts.** \"Ordering and Billing communicate via domain events, not synchronous HTTP.\"\n- **Technology choices that carry lock-in.** Database, message bus, auth provider, deployment target. Not every library: just the ones that would take a quarter to swap out.\n- **Boundary and scope decisions.** \"Customer data is owned by the Customer context; other contexts reference it by ID only.\" The explicit no-s are as valuable as the yes-s.\n- **Deliberate deviations from the obvious path.** \"We're using manual SQL instead of an ORM because X.\" Anything where a reasonable reader would assume the opposite. These stop the next engineer from \"fixing\" something that was deliberate.\n- **Constraints not visible in the code.** \"We can't use AWS because of compliance requirements.\" \"Response times must be under 200ms because of the partner API contract.\"\n- **Rejected alternatives when the rejection is non-obvious.** If you considered GraphQL and picked REST for subtle reasons, record it; otherwise someone will suggest GraphQL again in six months.\n"
|
|
42
|
+
"SKILL.md": "---\nname: domain-modeling\ndescription: Build and sharpen a project's domain model. Use when discussing codebase terminology, writing or editing a GLOSSARY.md, or recording or editing an ADR.\n---\n\n# Domain Modeling\n\nActively build and sharpen the project's domain model as you design. This is the *active* discipline: challenging terms, inventing edge-case scenarios, and writing the glossary and decisions down the moment they crystallise. (Merely *reading* `GLOSSARY.md` for vocabulary is not this skill: that's a one-line habit any skill can do. This skill is for when you're changing the model, not just consuming it.)\n\n## File structure\n\nMost repos have a single context:\n\n```\n/\n├── GLOSSARY.md\n├── docs/\n│ └── adr/\n│ ├── 0001-event-sourced-orders.md\n│ └── 0002-postgres-for-write-model.md\n└── src/\n```\n\nIf a `GLOSSARY-MAP.md` exists at the root, the repo has multiple contexts. The map points to where each one lives:\n\n```\n/\n├── GLOSSARY-MAP.md\n├── docs/\n│ └── adr/ <- system-wide decisions\n├── src/\n│ ├── ordering/\n│ │ ├── GLOSSARY.md\n│ │ └── docs/adr/ <- context-specific decisions\n│ └── billing/\n│ ├── GLOSSARY.md\n│ └── docs/adr/\n```\n\nCreate files lazily: only when you have something to write. If no `GLOSSARY.md` exists, create one when the first term is resolved. If no `docs/adr/` exists, create it when the first ADR is needed.\n\n## During the session\n\n### Challenge against the glossary\n\nWhen the user uses a term that conflicts with the existing language in `GLOSSARY.md`, call it out immediately. \"Your glossary defines 'cancellation' as X, but you seem to mean Y. Which is it?\"\n\n### Sharpen fuzzy language\n\nWhen the user uses vague or overloaded terms, propose a precise canonical term. \"You're saying 'account': do you mean the Customer or the User? Those are different things.\"\n\n### Discuss concrete scenarios\n\nWhen domain relationships are being discussed, stress-test them with specific scenarios. Invent scenarios that probe edge cases and force the user to be precise about the boundaries between concepts.\n\n### Cross-reference with code\n\nWhen the user states how something works, check whether the code agrees. If you find a contradiction, surface it: \"Your code cancels entire Orders, but you just said partial cancellation is possible. Which is right?\"\n\n### Update GLOSSARY.md inline\n\nWhen a term is resolved, update `GLOSSARY.md` right there. Don't batch these up: capture them as they happen. Use the format in [GLOSSARY-FORMAT.md](./GLOSSARY-FORMAT.md).\n\n`GLOSSARY.md` should be totally devoid of implementation details. Do not treat `GLOSSARY.md` as a spec, a scratch pad, or a repository for implementation decisions. It is a glossary and nothing else.\n\n### Offer ADRs sparingly\n\nOnly offer to create an ADR when all three are true:\n\n1. **Hard to reverse**: the cost of changing your mind later is meaningful\n2. **Surprising without context**: a future reader will wonder \"why did they do it this way?\"\n3. **The result of a real trade-off**: there were genuine alternatives and you picked one for specific reasons\n\nIf any of the three is missing, skip the ADR. Use the format in [ADR-FORMAT.md](./ADR-FORMAT.md).\n\n\nSource: mattpocock/skills (MIT); see THIRD_PARTY_NOTICES.\n\nFor public projects, exclude private material from project files. Do not stage or commit changes.\n",
|
|
43
|
+
"GLOSSARY-FORMAT.md": "# GLOSSARY.md Format\n\n## Structure\n\n```md\n# {Context Name}\n\n{One or two sentence description of what this context is and why it exists.}\n\n## Language\n\n**Order**:\n{A one or two sentence description of the term}\n_Avoid_: Purchase, transaction\n\n**Invoice**:\nA request for payment for an **Order**, sent to its **Customer** after delivery.\n_Avoid_: Bill, payment request\n\n**Customer**:\nA person or organization that places an **Order**.\n_Avoid_: Client, buyer, account\n```\n\n## Rules\n\n- **Be opinionated.** When multiple words exist for the same concept, pick the best one and list the others under `_Avoid_`.\n- **Keep definitions tight.** One or two sentences max. Define what it IS, not what it does.\n- **Bold other glossary terms inside a definition.** Write related terms as `**Order**` and describe how the terms relate.\n- **Only include terms specific to this project's context.** General programming concepts (timeouts, error types, utility patterns) don't belong even if the project uses them extensively. Before adding a term, ask: is this a concept unique to this context, or a general programming concept? Only the former belongs.\n- **Group terms under subheadings** when natural clusters emerge. If all terms belong to a single cohesive area, a flat list is fine.\n\n## Single vs multi-context repos\n\n**Single context (most repos):** One `GLOSSARY.md` at the repo root.\n\n**Multiple contexts:** A `GLOSSARY-MAP.md` at the repo root lists the contexts, where they live, and how they relate to each other:\n\n```md\n# Glossary Map\n\n## Contexts\n\n- [Ordering](./src/ordering/GLOSSARY.md): receives and tracks customer orders\n- [Billing](./src/billing/GLOSSARY.md): generates invoices and processes payments\n- [Fulfillment](./src/fulfillment/GLOSSARY.md): manages warehouse picking and shipping\n\n## Relationships\n\n- **Ordering -> Fulfillment**: Ordering emits `OrderPlaced` events; Fulfillment consumes them to start picking\n- **Fulfillment -> Billing**: Fulfillment emits `ShipmentDispatched` events; Billing consumes them to generate invoices\n- **Ordering ↔ Billing**: Shared types for `CustomerId` and `Money`\n```\n\nThe skill infers which structure applies:\n\n- If `GLOSSARY-MAP.md` exists, read it to find contexts\n- If only a root `GLOSSARY.md` exists, single context\n- If neither exists, create a root `GLOSSARY.md` lazily when the first term is resolved\n\nWhen multiple contexts exist, infer which one the current topic relates to. If unclear, ask.\n",
|
|
44
|
+
"ADR-FORMAT.md": "# ADR Format\n\nADRs live in `docs/adr/` and use sequential numbering: `0001-slug.md`, `0002-slug.md`, etc.\n\nCreate the `docs/adr/` directory lazily: only when the first ADR is needed.\n\n## Template\n\n```md\n# {Short title of the decision}\n\n{1-3 sentences: what's the context, what did we decide, and why.}\n```\n\nThat's it. An ADR can be a single paragraph. The value is in recording *that* a decision was made and *why*, not in filling out sections.\n\n## Optional sections\n\nOnly include these when they add genuine value. Most ADRs won't need them.\n\n- **Status** frontmatter (`proposed | accepted | deprecated | superseded by ADR-NNNN`): useful when decisions are revisited\n- **Considered Options**: only when the rejected alternatives are worth remembering\n- **Consequences**: only when non-obvious downstream effects need to be called out\n\n## When a decision changes\n\nWrite a new ADR explaining the new decision and why the old approach was replaced. Follow the project's convention for retaining, marking or linking superseded records.\n\n## Numbering\n\nScan `docs/adr/` for the highest existing number and increment by one.\n\n## When to offer an ADR\n\nAll three of these must be true:\n\n1. **Hard to reverse**: the cost of changing your mind later is meaningful\n2. **Surprising without context**: a future reader will look at the code and wonder \"why on earth did they do it this way?\"\n3. **The result of a real trade-off**: there were genuine alternatives and you picked one for specific reasons\n\nIf a decision is easy to reverse, skip it: you'll just reverse it. If it's not surprising, nobody will wonder why. If there was no real alternative, there's nothing to record beyond \"we did the obvious thing.\"\n\n### What qualifies\n\n- **Architectural shape.** \"We're using a monorepo.\" \"The write model is event-sourced, the read model is projected into Postgres.\"\n- **Integration patterns between contexts.** \"Ordering and Billing communicate via domain events, not synchronous HTTP.\"\n- **Technology choices that carry lock-in.** Database, message bus, auth provider, deployment target. Not every library: just the ones that would take a quarter to swap out.\n- **Boundary and scope decisions.** \"Customer data is owned by the Customer context; other contexts reference it by ID only.\" The explicit no-s are as valuable as the yes-s.\n- **Deliberate deviations from the obvious path.** \"We're using manual SQL instead of an ORM because X.\" Anything where a reasonable reader would assume the opposite. These stop the next engineer from \"fixing\" something that was deliberate.\n- **Constraints not visible in the code.** \"We can't use AWS because of compliance requirements.\" \"Response times must be under 200ms because of the partner API contract.\"\n- **Rejected alternatives when the rejection is non-obvious.** If you considered GraphQL and picked REST for subtle reasons, record it; otherwise someone will suggest GraphQL again in six months.\n"
|
|
39
45
|
}
|
|
40
46
|
},
|
|
41
47
|
{
|
|
@@ -56,7 +62,7 @@ export const THIRD_PARTY_SKILL_FILES: Array<{ slug: string; files: Record<string
|
|
|
56
62
|
{
|
|
57
63
|
"slug": "codebase-design",
|
|
58
64
|
"files": {
|
|
59
|
-
"SKILL.md": "---\nname: codebase-design\ndescription: Shared vocabulary for designing deep modules. Use when the user wants to design or improve a module's interface, find deepening opportunities, decide where a seam goes, make code more testable or AI-navigable, or when another skill needs the deep-module vocabulary.\n---\n\n# Codebase Design\n\nDesign **deep modules**: a lot of behaviour behind a small interface, placed at a clean seam, testable through that interface. Use this language and these principles wherever code is being designed or restructured. The aim is leverage for callers, locality for maintainers, and testability for everyone.\n\n## Glossary\n\nUse these terms exactly: don't substitute \"component,\" \"service,\" \"API,\" or \"boundary.\" Consistent language is the whole point.\n\n**Module**: anything with an interface and an implementation. Deliberately scale-agnostic: a function, class, package, or tier-spanning slice. _Avoid_: unit, component, service.\n\n**Interface**: everything a caller must know to use the module correctly: the type signature, but also invariants, ordering constraints, error modes, required configuration, and performance characteristics. _Avoid_: API, signature (too narrow, they refer only to the type-level surface).\n\n**Implementation**: what's inside a module, its body of code. Distinct from **Adapter**: a thing can be a small adapter with a large implementation (a Postgres repo) or a large adapter with a small implementation (an in-memory fake). Reach for \"adapter\" when the seam is the topic; \"implementation\" otherwise.\n\n**Depth**: leverage at the interface. The amount of behaviour a caller (or test) can exercise per unit of interface they have to learn. A module is **deep** when a large amount of behaviour sits behind a small interface, **shallow** when the interface is nearly as complex as the implementation.\n\n**Seam** _(Michael Feathers)_: a place where you can alter behaviour without editing in that place; the *location* at which a module's interface lives. Where to put the seam is its own design decision, distinct from what goes behind it. _Avoid_: boundary (overloaded with DDD's bounded context).\n\n**Adapter**: a concrete thing that satisfies an interface at a seam. Describes *role* (what slot it fills), not substance (what's inside).\n\n**Leverage**: what callers get from depth. More capability per unit of interface they learn. One implementation pays back across N call sites and M tests.\n\n**Locality**: what maintainers get from depth. Change, bugs, knowledge, and verification concentrate in one place rather than spreading across callers. Fix once, fixed everywhere.\n\n## Deep vs shallow\n\n**Deep module** = small interface + lots of implementation:\n\n```\n
|
|
65
|
+
"SKILL.md": "---\nname: codebase-design\ndescription: Shared vocabulary for designing deep modules. Use when the user wants to design or improve a module's interface, find deepening opportunities, decide where a seam goes, make code more testable or AI-navigable, or when another skill needs the deep-module vocabulary.\n---\n\n# Codebase Design\n\nDesign **deep modules**: a lot of behaviour behind a small interface, placed at a clean seam, testable through that interface. Use this language and these principles wherever code is being designed or restructured. The aim is leverage for callers, locality for maintainers, and testability for everyone.\n\n## Glossary\n\nUse these terms exactly: don't substitute \"component,\" \"service,\" \"API,\" or \"boundary.\" Consistent language is the whole point.\n\n**Module**: anything with an interface and an implementation. Deliberately scale-agnostic: a function, class, package, or tier-spanning slice. _Avoid_: unit, component, service.\n\n**Interface**: everything a caller must know to use the module correctly: the type signature, but also invariants, ordering constraints, error modes, required configuration, and performance characteristics. _Avoid_: API, signature (too narrow, they refer only to the type-level surface).\n\n**Implementation**: what's inside a module, its body of code. Distinct from **Adapter**: a thing can be a small adapter with a large implementation (a Postgres repo) or a large adapter with a small implementation (an in-memory fake). Reach for \"adapter\" when the seam is the topic; \"implementation\" otherwise.\n\n**Depth**: leverage at the interface. The amount of behaviour a caller (or test) can exercise per unit of interface they have to learn. A module is **deep** when a large amount of behaviour sits behind a small interface, **shallow** when the interface is nearly as complex as the implementation.\n\n**Seam** _(Michael Feathers)_: a place where you can alter behaviour without editing in that place; the *location* at which a module's interface lives. Where to put the seam is its own design decision, distinct from what goes behind it. _Avoid_: boundary (overloaded with DDD's bounded context).\n\n**Adapter**: a concrete thing that satisfies an interface at a seam. Describes *role* (what slot it fills), not substance (what's inside).\n\n**Leverage**: what callers get from depth. More capability per unit of interface they learn. One implementation pays back across N call sites and M tests.\n\n**Locality**: what maintainers get from depth. Change, bugs, knowledge, and verification concentrate in one place rather than spreading across callers. Fix once, fixed everywhere.\n\n## Deep vs shallow\n\n**Deep module** = small interface + lots of implementation:\n\n```\n┌─────────────────────┐\n│ Small Interface │ <- Few methods, simple params\n├─────────────────────┤\n│ │\n│ Deep Implementation│ <- Complex logic hidden\n│ │\n└─────────────────────┘\n```\n\n**Shallow module** = large interface + little implementation (avoid):\n\n```\n┌─────────────────────────────────┐\n│ Large Interface │ <- Many methods, complex params\n├─────────────────────────────────┤\n│ Thin Implementation │ <- Just passes through\n└─────────────────────────────────┘\n```\n\nWhen designing an interface, ask:\n\n- Can I reduce the number of methods?\n- Can I simplify the parameters?\n- Can I hide more complexity inside?\n\n## Principles\n\n- **Depth is a property of the interface, not the implementation.** A deep module can be internally composed of small, mockable, swappable parts; they just aren't part of the interface. A module can have **internal seams** (private to its implementation, used by its own tests) as well as the **external seam** at its interface.\n- **The deletion test.** Imagine deleting the module. If complexity vanishes, it was a pass-through. If complexity reappears across N callers, it was earning its keep.\n- **The interface is the test surface.** Callers and tests cross the same seam. If you want to test *past* the interface, the module is probably the wrong shape.\n- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a seam unless something actually varies across it.\n\n## Designing for testability\n\nGood interfaces make testing natural:\n\n1. **Accept dependencies, don't create them.**\n\n ```typescript\n // Testable\n function processOrder(order, paymentGateway) {}\n\n // Hard to test\n function processOrder(order) {\n const gateway = new StripeGateway();\n }\n ```\n\n2. **Return results, don't produce side effects.**\n\n ```typescript\n // Testable\n function calculateDiscount(cart): Discount {}\n\n // Hard to test\n function applyDiscount(cart): void {\n cart.total -= discount;\n }\n ```\n\n3. **Small surface area.** Fewer methods = fewer tests needed. Fewer params = simpler test setup.\n\n## Relationships\n\n- A **Module** has exactly one **Interface** (the surface it presents to callers and tests).\n- **Depth** is a property of a **Module**, measured against its **Interface**.\n- A **Seam** is where a **Module**'s **Interface** lives.\n- An **Adapter** sits at a **Seam** and satisfies the **Interface**.\n- **Depth** produces **Leverage** for callers and **Locality** for maintainers.\n\n## Rejected framings\n\n- **Depth as ratio of implementation-lines to interface-lines** (Ousterhout): rewards padding the implementation. We use depth-as-leverage instead.\n- **\"Interface\" as the TypeScript `interface` keyword or a class's public methods**: too narrow: interface here includes every fact a caller must know.\n- **\"Boundary\"**: overloaded with DDD's bounded context. Say **seam** or **interface**.\n\n## Going deeper\n\n- **Deepening a cluster given its dependencies**, see [DEEPENING.md](DEEPENING.md): dependency categories, seam discipline, and replace-don't-layer testing.\n- **Exploring alternative interfaces**, see [DESIGN-IT-TWICE.md](DESIGN-IT-TWICE.md): spin up parallel sub-agents to design the interface several radically different ways, then compare on depth, locality, and seam placement.\n\n\nSource: mattpocock/skills (MIT); see THIRD_PARTY_NOTICES.\n",
|
|
60
66
|
"DESIGN-IT-TWICE.md": "# Design It Twice\n\nWhen the user wants to explore alternative interfaces for a chosen deepening candidate, use this parallel sub-agent pattern. Based on \"Design It Twice\" (Ousterhout): your first idea is unlikely to be the best.\n\nUses the vocabulary in [SKILL.md](SKILL.md): **module**, **interface**, **seam**, **adapter**, **leverage**.\n\n## Process\n\n### 1. Frame the problem space\n\nBefore spawning sub-agents, write a user-facing explanation of the problem space for the chosen candidate:\n\n- The constraints any new interface would need to satisfy\n- The dependencies it would rely on, and which category they fall into (see [DEEPENING.md](DEEPENING.md))\n- A rough illustrative code sketch to ground the constraints, not a proposal, just a way to make the constraints concrete\n\nShow this to the user, then immediately proceed to Step 2. The user reads and thinks while the sub-agents work in parallel.\n\n### 2. Spawn sub-agents\n\nSpawn 3+ sub-agents in parallel, each with a fresh context window. Each must produce a **radically different** interface for the deepened module.\n\nPrompt each sub-agent with a separate technical brief (file paths, coupling details, dependency category from [DEEPENING.md](DEEPENING.md), what sits behind the seam). The brief is independent of the user-facing problem-space explanation in Step 1. Give each agent a different design constraint:\n\n- Agent 1: \"Minimize the interface: aim for 1-3 entry points max. Maximise leverage per entry point.\"\n- Agent 2: \"Maximise flexibility: support many use cases and extension.\"\n- Agent 3: \"Optimise for the most common caller: make the default case trivial.\"\n- Agent 4 (if applicable): \"Design around ports & adapters for cross-seam dependencies.\"\n\nInclude both [SKILL.md](SKILL.md) vocabulary and GLOSSARY.md vocabulary in the brief so each sub-agent names things consistently with the architecture language and the project's domain language.\n\nEach sub-agent outputs:\n\n1. Interface (types, methods, params, plus invariants, ordering, error modes)\n2. Usage example showing how callers use it\n3. What the implementation hides behind the seam\n4. Dependency strategy and adapters (see [DEEPENING.md](DEEPENING.md))\n5. Trade-offs: where leverage is high, where it's thin\n\n### 3. Present and compare\n\nPresent designs sequentially so the user can absorb each one, then compare them in prose. Contrast by **depth** (leverage at the interface), **locality** (where change concentrates), and **seam placement**.\n\nAfter comparing, give your own recommendation: which design you think is strongest and why. If elements from different designs would combine well, propose a hybrid. Be opinionated: the user wants a strong read, not a menu.\n",
|
|
61
67
|
"DEEPENING.md": "# Deepening\n\nHow to deepen a cluster of shallow modules safely, given its dependencies. Assumes the vocabulary in [SKILL.md](SKILL.md): **module**, **interface**, **seam**, **adapter**.\n\n## Dependency categories\n\nWhen assessing a candidate for deepening, classify its dependencies. The category determines how the deepened module is tested across its seam.\n\n### 1. In-process\n\nPure computation, in-memory state, no I/O. Always deepenable: merge the modules and test through the new interface directly. No adapter needed.\n\n### 2. Local-substitutable\n\nDependencies that have local test stand-ins (PGLite for Postgres, in-memory filesystem). Deepenable if the stand-in exists. The deepened module is tested with the stand-in running in the test suite. The seam is internal; no port at the module's external interface.\n\n### 3. Remote but owned (Ports & Adapters)\n\nYour own services across a network boundary (microservices, internal APIs). Define a **port** (interface) at the seam. The deep module owns the logic; the transport is injected as an **adapter**. Tests use an in-memory adapter. Production uses an HTTP/gRPC/queue adapter.\n\nRecommendation shape: *\"Define a port at the seam, implement an HTTP adapter for production and an in-memory adapter for testing, so the logic sits in one deep module even though it's deployed across a network.\"*\n\n### 4. True external (Mock)\n\nThird-party services (Stripe, Twilio, etc.) you don't control. The deepened module takes the external dependency as an injected port; tests provide a mock adapter.\n\n## Seam discipline\n\n- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a port unless at least two adapters are justified (typically production + test). A single-adapter seam is just indirection.\n- **Internal seams vs external seams.** A deep module can have internal seams (private to its implementation, used by its own tests) as well as the external seam at its interface. Don't expose internal seams through the interface just because tests use them.\n\n## Testing strategy: replace, don't layer\n\n- Old unit tests on shallow modules become waste once tests at the deepened module's interface exist; delete them.\n- Write new tests at the deepened module's interface. The **interface is the test surface**.\n- Tests assert on observable outcomes through the interface, not internal state.\n- Tests should survive internal refactors, since they describe behaviour, not implementation. If a test has to change when the implementation changes, it's testing past the interface.\n"
|
|
62
68
|
}
|
|
@@ -61,14 +61,15 @@ export async function summarizeTurnChanges(cwd: string, from: string, to: string
|
|
|
61
61
|
} catch { return null; }
|
|
62
62
|
}
|
|
63
63
|
|
|
64
|
-
// A timed-out pre-turn capture
|
|
65
|
-
//
|
|
66
|
-
|
|
64
|
+
// A timed-out pre-turn capture is never used: the worker can already be
|
|
65
|
+
// editing by then and the ref is not a safe baseline. `onTimeout` lets the
|
|
66
|
+
// caller cancel it so it stops and publishes nothing.
|
|
67
|
+
export async function timelyCheckpoint<T>(capture: Promise<T | null>, timeoutMs = 2000, onTimeout?: () => void): Promise<T | null> {
|
|
67
68
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
68
69
|
try {
|
|
69
70
|
return await Promise.race([
|
|
70
71
|
capture.catch(() => null),
|
|
71
|
-
new Promise<null>(resolve => { timer = setTimeout(() => resolve(null), timeoutMs); }),
|
|
72
|
+
new Promise<null>(resolve => { timer = setTimeout(() => { onTimeout?.(); resolve(null); }, timeoutMs); }),
|
|
72
73
|
]);
|
|
73
74
|
} finally { if (timer) clearTimeout(timer); }
|
|
74
75
|
}
|
package/server/src/usage.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { join } from 'path';
|
|
|
3
3
|
import { homedir } from 'os';
|
|
4
4
|
import { createHash } from 'node:crypto';
|
|
5
5
|
import type { ClaudeCredentialBinding, UsageInfo } from '@arco/shared';
|
|
6
|
+
import { requireClaudeNativeAccount } from './providerAccounts.js';
|
|
6
7
|
import { loadTokens, nativeCredentialBinding } from './providers/claude-native/auth.js';
|
|
7
8
|
import { ensureLiveTokens as ensureClaudeNativeTokens, REFRESH_LEAD_MS_EXPORT } from './providers/claude-native/oauth.js';
|
|
8
9
|
|
|
@@ -29,11 +30,11 @@ let checkSequence = 0;
|
|
|
29
30
|
|
|
30
31
|
// Read current revisions before considering cached data. Native refresh stays
|
|
31
32
|
// with its credential owner and happens only on a cache miss before a request.
|
|
32
|
-
async function readNativeCredentials(): Promise<LiveTokens | null> {
|
|
33
|
-
const tokens = await loadTokens();
|
|
33
|
+
async function readNativeCredentials(accountRef?: string): Promise<LiveTokens | null> {
|
|
34
|
+
const tokens = await loadTokens(accountRef);
|
|
34
35
|
if (!tokens) return null;
|
|
35
36
|
if (typeof tokens.accessToken !== 'string' || !tokens.accessToken || typeof tokens.refreshToken !== 'string' || !tokens.refreshToken || !Number.isFinite(tokens.expiresAt)) throw new Error('Invalid Native credentials');
|
|
36
|
-
return { accessToken: tokens.accessToken, expiresAt: tokens.expiresAt, subscriptionType: 'claude-native', source: 'claude-native', binding: nativeCredentialBinding(tokens) };
|
|
37
|
+
return { accessToken: tokens.accessToken, expiresAt: tokens.expiresAt, subscriptionType: 'claude-native', source: 'claude-native', binding: nativeCredentialBinding(tokens, accountRef) };
|
|
37
38
|
}
|
|
38
39
|
|
|
39
40
|
async function readCliCredentials(): Promise<LiveTokens | null> {
|
|
@@ -56,13 +57,15 @@ export async function getCliUsageBinding(): Promise<ClaudeCredentialBinding> {
|
|
|
56
57
|
return (await getCliTokens().catch(() => null))?.binding ?? { source: 'claude-cli', storeId: 'claude-cli-default' };
|
|
57
58
|
}
|
|
58
59
|
|
|
59
|
-
async function getTokenCandidates(): Promise<Candidates> {
|
|
60
|
+
async function getTokenCandidates(accountRef?: string): Promise<Candidates> {
|
|
60
61
|
const tokens: LiveTokens[] = [], errors: string[] = [];
|
|
61
|
-
try { const native = await readNativeCredentials(); if (native) tokens.push(native); }
|
|
62
|
+
try { const native = await readNativeCredentials(accountRef); if (native) tokens.push(native); }
|
|
62
63
|
catch { errors.push('Native allowance credentials could not be read'); }
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
64
|
+
if (accountRef === undefined) {
|
|
65
|
+
try { const cli = await getCliTokens(); if (cli) tokens.push(cli); }
|
|
66
|
+
catch { errors.push('CLI allowance credentials could not be read'); }
|
|
67
|
+
}
|
|
68
|
+
return { tokens, errors, key: JSON.stringify([accountRef, tokens.map(t => t.binding), errors]) };
|
|
66
69
|
}
|
|
67
70
|
|
|
68
71
|
function unavailable(checkedAt: number, error: string, stale = false): UsageInfo {
|
|
@@ -73,9 +76,9 @@ function unavailable(checkedAt: number, error: string, stale = false): UsageInfo
|
|
|
73
76
|
function changed(checkedAt: number): UsageInfo {
|
|
74
77
|
return unavailable(checkedAt, 'Credentials changed while checking allowance. Check again for the current credential source.', true);
|
|
75
78
|
}
|
|
76
|
-
function credentialContext(context: Candidates): NonNullable<UsageInfo['credentialContext']> {
|
|
79
|
+
function credentialContext(context: Candidates, accountRef?: string): NonNullable<UsageInfo['credentialContext']> {
|
|
77
80
|
return {
|
|
78
|
-
native: context.tokens.find(t => t.source === 'claude-native')?.binding ??
|
|
81
|
+
native: context.tokens.find(t => t.source === 'claude-native')?.binding ?? nativeCredentialBinding(null, accountRef),
|
|
79
82
|
cli: context.tokens.find(t => t.source === 'claude-cli')?.binding ?? { source: 'claude-cli', storeId: 'claude-cli-default' },
|
|
80
83
|
};
|
|
81
84
|
}
|
|
@@ -96,19 +99,19 @@ function windowValue(raw: unknown): UsageInfo['session'] {
|
|
|
96
99
|
return { utilization: value.utilization, resetsAt: typeof value.resets_at === 'string' ? value.resets_at : null };
|
|
97
100
|
}
|
|
98
101
|
|
|
99
|
-
async function checkUsage(initial: Candidates, sequence: number): Promise<UsageInfo> {
|
|
102
|
+
async function checkUsage(initial: Candidates, sequence: number, accountRef?: string): Promise<UsageInfo> {
|
|
100
103
|
let context = initial;
|
|
101
104
|
const checkedAt = Date.now(), errors = [...initial.errors];
|
|
102
105
|
for (let index = 0; index < initial.tokens.length; index++) {
|
|
103
106
|
let tokens = initial.tokens[index];
|
|
104
|
-
if (index && (await getTokenCandidates()).key !== context.key) return changed(checkedAt);
|
|
107
|
+
if (index && (await getTokenCandidates(accountRef)).key !== context.key) return changed(checkedAt);
|
|
105
108
|
try {
|
|
106
109
|
if (tokens.source === 'claude-native' && tokens.expiresAt <= Date.now() + REFRESH_LEAD_MS_EXPORT) {
|
|
107
110
|
// Preserve the Native owner's existing locking and expiry refresh.
|
|
108
111
|
// No allowance failure marks execution auth or invokes forced refresh.
|
|
109
|
-
const refreshed = await ensureClaudeNativeTokens();
|
|
110
|
-
const binding = nativeCredentialBinding(refreshed);
|
|
111
|
-
const next = await getTokenCandidates();
|
|
112
|
+
const refreshed = await ensureClaudeNativeTokens(accountRef);
|
|
113
|
+
const binding = nativeCredentialBinding(refreshed, accountRef);
|
|
114
|
+
const next = await getTokenCandidates(accountRef);
|
|
112
115
|
if (next.tokens.find(t => t.source === 'claude-native')?.binding.revision !== binding.revision
|
|
113
116
|
|| next.tokens.find(t => t.source === 'claude-cli')?.binding.revision !== context.tokens.find(t => t.source === 'claude-cli')?.binding.revision) return changed(checkedAt);
|
|
114
117
|
context = next;
|
|
@@ -123,33 +126,38 @@ async function checkUsage(initial: Candidates, sequence: number): Promise<UsageI
|
|
|
123
126
|
const session = windowValue(data.five_hour), weekly = windowValue(data.seven_day);
|
|
124
127
|
if (!session && !weekly) { errors.push(`No allowance windows returned (${tokens.source})`); continue; }
|
|
125
128
|
// Reading the revisions AFTER parsing also fences delayed response bodies.
|
|
126
|
-
if ((await getTokenCandidates()).key !== context.key) return changed(checkedAt);
|
|
129
|
+
if ((await getTokenCandidates(accountRef)).key !== context.key) return changed(checkedAt);
|
|
127
130
|
const info: UsageInfo = { session, weekly, subscriptionType: tokens.subscriptionType, fetchedAt: Date.now(), checkedAt,
|
|
128
131
|
source: tokens.source, binding: tokens.binding, identity: { state: 'unknown' }, available: true, stale: false,
|
|
129
|
-
credentialContext: credentialContext(context),
|
|
132
|
+
credentialContext: credentialContext(context, accountRef),
|
|
130
133
|
freshness: 'fresh', fallback: tokens.source === 'claude-cli' && (index > 0 || initial.errors.length > 0) };
|
|
131
134
|
return remember(context.key, info, sequence);
|
|
132
135
|
} catch {
|
|
133
136
|
errors.push(`Allowance request failed (${tokens.source}); execution authentication is unchanged`);
|
|
134
137
|
}
|
|
135
138
|
}
|
|
136
|
-
if ((await getTokenCandidates()).key !== context.key) return changed(checkedAt);
|
|
139
|
+
if ((await getTokenCandidates(accountRef)).key !== context.key) return changed(checkedAt);
|
|
137
140
|
const error = `${errors.join('; ') || 'No suitable Claude OAuth allowance credentials found'}. Allowance availability is separate from execution authentication.`;
|
|
138
141
|
const previous = cache.get(context.key)?.value;
|
|
139
142
|
const info = previous?.binding && (previous.session || previous.weekly)
|
|
140
143
|
? { ...previous, available: false, stale: true, freshness: 'stale' as const, checkedAt, error }
|
|
141
|
-
: { ...unavailable(checkedAt, error), credentialContext: credentialContext(context) };
|
|
144
|
+
: { ...unavailable(checkedAt, error), credentialContext: credentialContext(context, accountRef) };
|
|
142
145
|
return remember(context.key, info, sequence);
|
|
143
146
|
}
|
|
144
147
|
|
|
145
|
-
export async function getUsage(force = false): Promise<UsageInfo> {
|
|
146
|
-
|
|
148
|
+
export async function getUsage(force = false, requestedAccount?: string): Promise<UsageInfo> {
|
|
149
|
+
let accountRef: string | undefined;
|
|
150
|
+
if (requestedAccount !== undefined) {
|
|
151
|
+
try { accountRef = await requireClaudeNativeAccount(requestedAccount); }
|
|
152
|
+
catch { return unavailable(Date.now(), 'The selected Claude Native account is unavailable.'); }
|
|
153
|
+
}
|
|
154
|
+
const candidates = await getTokenCandidates(accountRef);
|
|
147
155
|
const pending = inFlight.get(candidates.key);
|
|
148
156
|
if (pending) return pending;
|
|
149
157
|
const cached = cache.get(candidates.key);
|
|
150
158
|
if (!force && cached && Date.now() - cached.cachedAt < CACHE_TTL_MS) return fromCache(cached);
|
|
151
159
|
const sequence = ++checkSequence;
|
|
152
|
-
const promise = Promise.resolve().then(() => checkUsage(candidates, sequence)).finally(() => {
|
|
160
|
+
const promise = Promise.resolve().then(() => checkUsage(candidates, sequence, accountRef)).finally(() => {
|
|
153
161
|
if (inFlight.get(candidates.key) === promise) inFlight.delete(candidates.key);
|
|
154
162
|
});
|
|
155
163
|
inFlight.set(candidates.key, promise);
|
|
@@ -132,6 +132,7 @@ export class WorkerManager {
|
|
|
132
132
|
sandbox?: WorkerConfig['sandbox'];
|
|
133
133
|
interactionMode?: WorkerConfig['interactionMode'];
|
|
134
134
|
antigravityInteractive?: boolean;
|
|
135
|
+
antigravityHandoffWriter?: boolean;
|
|
135
136
|
antigravityChatWorkspace?: boolean;
|
|
136
137
|
disableProviderHooks?: boolean;
|
|
137
138
|
// Chat-only web-tool arming; ignored by agent-mode spawns.
|
|
@@ -292,6 +293,7 @@ export class WorkerManager {
|
|
|
292
293
|
sandbox: options?.sandbox,
|
|
293
294
|
interactionMode: options?.interactionMode,
|
|
294
295
|
antigravityInteractive: options?.antigravityInteractive,
|
|
296
|
+
antigravityHandoffWriter: options?.antigravityHandoffWriter,
|
|
295
297
|
antigravityChatWorkspace: options?.antigravityChatWorkspace,
|
|
296
298
|
disableProviderHooks: options?.disableProviderHooks,
|
|
297
299
|
chatWebAccess: options?.chatWebAccess,
|