@commonlyai/cli 0.1.263 → 0.1.265
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/node_modules/@commonlyai/seats/src/upstream-refusal.js +34 -0
- package/package.json +1 -1
- package/skills/commonly/SKILL.md +7 -5
- package/src/commands/agent.js +75 -7
- package/src/lib/adapters/claude.js +24 -0
- package/src/lib/adapters/opencode.js +488 -9
- package/src/lib/adapters/pi.js +2 -2
- package/src/lib/default-environment.js +6 -4
- package/src/lib/grant-broker-guard.js +8 -3
- package/src/lib/model-unavailable.js +134 -0
- package/src/lib/sandbox/bwrap.js +10 -3
- package/src/lib/sandbox/seatbelt.js +19 -0
- package/src/lib/sandbox/workspace-pin.js +158 -0
- package/src/lib/session-store.js +43 -1
- package/src/lib/workspace-trust.js +2 -2
|
@@ -193,6 +193,12 @@ export const confinementReason = (environment, adapter, platform = process.platf
|
|
|
193
193
|
return null;
|
|
194
194
|
};
|
|
195
195
|
|
|
196
|
+
/** "claude, codex or opencode": the broker set, as a remedy names it. */
|
|
197
|
+
const brokerAdapterList = () => {
|
|
198
|
+
const names = [...ADAPTERS_WITH_GRANT_BROKER];
|
|
199
|
+
return names.length > 1 ? `${names.slice(0, -1).join(', ')} or ${names[names.length - 1]}` : names.join('');
|
|
200
|
+
};
|
|
201
|
+
|
|
196
202
|
const detailFor = (reason, adapter, environment, platform = process.platform) => {
|
|
197
203
|
const drop = 'or drop the grant broker from this seat';
|
|
198
204
|
if (reason === 'sandbox_mode_unenforceable' && platform === 'win32') {
|
|
@@ -201,11 +207,10 @@ const detailFor = (reason, adapter, environment, platform = process.platform) =>
|
|
|
201
207
|
}
|
|
202
208
|
if (reason === 'adapter_cannot_confine') {
|
|
203
209
|
return `the seat runs the '${adapter || 'unresolved'}' adapter, which is not approved to receive the grant broker;`
|
|
204
|
-
+
|
|
205
|
-
+ ` adapter, ${drop}`;
|
|
210
|
+
+ ` move this seat to the ${brokerAdapterList()} adapter, ${drop}`;
|
|
206
211
|
}
|
|
207
212
|
if (reason === 'sandbox_absent') {
|
|
208
|
-
return 'this seat declares no sandbox block and
|
|
213
|
+
return 'this seat declares no sandbox block and none was derived for it,'
|
|
209
214
|
+ ` so it would run with a granter's authority and no confinement; declare sandbox.trust 'public' ${drop}`;
|
|
210
215
|
}
|
|
211
216
|
if (reason === 'sandbox_mode_none') {
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* F178 — a turn the model provider refused because the model itself is not
|
|
3
|
+
* available, and the one line the wrapper posts about it.
|
|
4
|
+
*
|
|
5
|
+
* Found on a Growth walk, 2026-11-05: a daemon seat with no server-side model
|
|
6
|
+
* ran claude with a model the person's Anthropic key was not scoped for. Every
|
|
7
|
+
* turn failed with "403 The requested model ... is not available for this API
|
|
8
|
+
* key", the seat log said so, and the pod said nothing. The person saw a silent
|
|
9
|
+
* agent and no way to fix it.
|
|
10
|
+
*
|
|
11
|
+
* The match is deliberately narrow. A 403 or 404 alone is not a model problem:
|
|
12
|
+
* a disabled organization, a revoked key and a wrong route all answer 403/404,
|
|
13
|
+
* and telling that person to change the model would send them the wrong way.
|
|
14
|
+
* So a failure counts only when it carries one of these shapes:
|
|
15
|
+
*
|
|
16
|
+
* 1. claude / Anthropic 403: "... model ... is not available for this API key",
|
|
17
|
+
* with the 403 attached as the status or on the phrase's own line
|
|
18
|
+
* 2. OpenAI-style error code `model_not_found` (codex, opencode, LiteLLM), as
|
|
19
|
+
* the structured `providerCode` adapterFailure keeps, not message text
|
|
20
|
+
* 3. a 404 whose text is model-shaped, on the same line or in one JSON
|
|
21
|
+
* error body: Anthropic's `not_found_error` body,
|
|
22
|
+
* kept as "model: <id>" by the adapter's keep-list, or "The model `<id>`
|
|
23
|
+
* does not exist", or "model <id> not found".
|
|
24
|
+
*
|
|
25
|
+
* A public seat's withheld-tool error quotes a TOOL's vendor text, not the
|
|
26
|
+
* turn's own provider, so it never counts (public-tool-error.js).
|
|
27
|
+
*/
|
|
28
|
+
import { PUBLIC_MCP_NOT_READY_CODE, PUBLIC_TOOL_FAILED_CODE } from './public-tool-error.js';
|
|
29
|
+
|
|
30
|
+
/** How long one model's hint stays posted before the seat may post it again. */
|
|
31
|
+
export const MODEL_UNAVAILABLE_HINT_WINDOW_MS = 60 * 60 * 1000;
|
|
32
|
+
|
|
33
|
+
const NOT_AVAILABLE_FOR_KEY_RE = /\bmodel\b[^\n]{0,160}?\bis not available for (?:this|your) API key\b/i;
|
|
34
|
+
// A status read out of text counts only where a status is written: at a line
|
|
35
|
+
// start, just inside a bracket, or after an explicit HTTP, HTTP/1.1, HTTP status,
|
|
36
|
+
// status, status_code, code, our own `upstream` label (adapterFailure's "(upstream 404)") or
|
|
37
|
+
// claude's `API Error`, each with an optional `:`, `=`, `_` or `-`. It is never
|
|
38
|
+
// followed by a word character, `.` or `-`. So `request_id=404`, `gpt-404-mini`
|
|
39
|
+
// and `claude-403x` are not statuses.
|
|
40
|
+
const statusRe = (code) => new RegExp('(?:^\\s*|[([{]\\s*|\\b(?:HTTP(?:/\\d(?:\\.\\d)?|\\s+status)?'
|
|
41
|
+
+ `|status(?:_?code)?|code|upstream|API\\s+Error)\\s*[:=_-]?\\s*)${code}(?![\\w.-])`, 'i');
|
|
42
|
+
const STATUS_403_RE = statusRe(403);
|
|
43
|
+
const MODEL_404_SHAPES = [
|
|
44
|
+
/\bmodel:\s*[`'"]?[\w.:/@-]+/i,
|
|
45
|
+
/\bthe model\b[^\n]{0,120}?\bdoes not exist\b/i,
|
|
46
|
+
/\bmodel\b[^\n]{0,120}?\bnot found\b/i,
|
|
47
|
+
];
|
|
48
|
+
const STATUS_404_RE = statusRe(404);
|
|
49
|
+
const modelShaped = (text) => MODEL_404_SHAPES.some((pattern) => pattern.test(text));
|
|
50
|
+
|
|
51
|
+
// A 404 counts only when the status and the model shape are one statement: the
|
|
52
|
+
// same line, or one JSON error body. An unrelated 404 on one stderr line must
|
|
53
|
+
// not be joined to a model mentioned on another.
|
|
54
|
+
const sameLine404 = (text) => text.split('\n').some((line) => STATUS_404_RE.test(line) && modelShaped(line));
|
|
55
|
+
|
|
56
|
+
const jsonBody404 = (text) => {
|
|
57
|
+
const start = text.indexOf('{');
|
|
58
|
+
const end = text.lastIndexOf('}');
|
|
59
|
+
if (start < 0 || end <= start) return false;
|
|
60
|
+
let parsed;
|
|
61
|
+
try {
|
|
62
|
+
parsed = JSON.parse(text.slice(start, end + 1));
|
|
63
|
+
} catch {
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return false;
|
|
67
|
+
const error = parsed.error && typeof parsed.error === 'object' ? parsed.error : parsed;
|
|
68
|
+
const is404 = [parsed.status, parsed.code, error.status, error.code]
|
|
69
|
+
.some((value) => String(value) === '404') || error.type === 'not_found_error';
|
|
70
|
+
const message = error.message ?? parsed.message;
|
|
71
|
+
return is404 && typeof message === 'string' && modelShaped(message);
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
// The model id, when the provider named it. Only this charset is ever echoed
|
|
75
|
+
// into a pod, so provider prose and anything redacted (`[redacted]`) cannot be.
|
|
76
|
+
const MODEL_NAME_RES = [
|
|
77
|
+
/\brequested model\s+[`'"]?([\w.:/@-]+?)[`'"]?\s+is not available\b/i,
|
|
78
|
+
/\bmodel:\s*[`'"]?([\w.:/@-]+)/i,
|
|
79
|
+
/\bmodel\s+[`'"]([\w.:/@-]+)[`'"]/i,
|
|
80
|
+
/\bmodel\s+([\w.:/@-]+)\s+(?:not found|does not exist)\b/i,
|
|
81
|
+
];
|
|
82
|
+
// An id read out of prose must look like one ("is", "not" never do); a seat's
|
|
83
|
+
// own configured model may be a bare alias such as `sonnet`.
|
|
84
|
+
const ID_LIKE_RE = /[\d.:/-]/;
|
|
85
|
+
const SAFE_MODEL_RE = /^(?=.*[A-Za-z])[\w.:/@-]{1,100}$/;
|
|
86
|
+
|
|
87
|
+
const failureText = (error) => [error?.message, error?.stderr, error?.body?.error, error?.body?.message]
|
|
88
|
+
.filter((value) => typeof value === 'string' && value)
|
|
89
|
+
.join('\n');
|
|
90
|
+
|
|
91
|
+
export const safeModelName = (value) => {
|
|
92
|
+
const text = typeof value === 'string' ? value.trim() : '';
|
|
93
|
+
// A leading `@` would read as a mention in the pod, and `://` as a link.
|
|
94
|
+
if (text.startsWith('@') || text.includes('://')) return null;
|
|
95
|
+
return SAFE_MODEL_RE.test(text) ? text : null;
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* `{ model }` when the failure is a provider saying the model is unavailable,
|
|
100
|
+
* else null. `model` is the id the provider named, then `fallbackModel` (the
|
|
101
|
+
* seat's own setting), then null when neither is known.
|
|
102
|
+
*/
|
|
103
|
+
export const modelUnavailableFailure = (error, { fallbackModel = null } = {}) => {
|
|
104
|
+
if (!error || error.code === PUBLIC_TOOL_FAILED_CODE || error.code === PUBLIC_MCP_NOT_READY_CODE) return null;
|
|
105
|
+
const text = failureText(error);
|
|
106
|
+
if (!text) return null;
|
|
107
|
+
// The key-scope phrase counts only on a 403: the attached status, or a 403 on
|
|
108
|
+
// the phrase's own line. The provider's code counts only as the structured
|
|
109
|
+
// field adapterFailure keeps, never as words in a message.
|
|
110
|
+
// An attached status is the adapter's own reading of the failure, so it wins:
|
|
111
|
+
// when it is set, only that status decides, and the text is not searched for
|
|
112
|
+
// another one. Without it, the status must be written on the same line.
|
|
113
|
+
const attached = typeof error.status === 'number' ? error.status : null;
|
|
114
|
+
const lines = text.split('\n');
|
|
115
|
+
const keyScope = NOT_AVAILABLE_FOR_KEY_RE.test(text) && (attached !== null ? attached === 403
|
|
116
|
+
: lines.some((line) => STATUS_403_RE.test(line) && NOT_AVAILABLE_FOR_KEY_RE.test(line)));
|
|
117
|
+
const notFound = attached !== null
|
|
118
|
+
? attached === 404 && (lines.some(modelShaped) || jsonBody404(text))
|
|
119
|
+
: sameLine404(text) || jsonBody404(text);
|
|
120
|
+
const matched = keyScope
|
|
121
|
+
|| error.providerCode === 'model_not_found'
|
|
122
|
+
|| notFound;
|
|
123
|
+
if (!matched) return null;
|
|
124
|
+
for (const pattern of MODEL_NAME_RES) {
|
|
125
|
+
const named = safeModelName(pattern.exec(text)?.[1]);
|
|
126
|
+
if (named && ID_LIKE_RE.test(named)) return { model: named };
|
|
127
|
+
}
|
|
128
|
+
return { model: safeModelName(fallbackModel) };
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
/** The one line posted in the pod. */
|
|
132
|
+
export const modelUnavailableHint = (model) => (model
|
|
133
|
+
? `The model provider says ${model} isn't available for this agent. To change it, open the agent's Settings, then Model.`
|
|
134
|
+
: "The model provider says this agent's model isn't available. To change it, open the agent's Settings, then Model.");
|
package/src/lib/sandbox/bwrap.js
CHANGED
|
@@ -178,7 +178,14 @@ export const wrapArgvWithBwrap = (innerArgv, env, opts = {}) => {
|
|
|
178
178
|
flags.push('--bind', p, p);
|
|
179
179
|
}
|
|
180
180
|
|
|
181
|
-
|
|
181
|
+
// The folder mounted at workspacePath: workspaceSource when the caller has
|
|
182
|
+
// already resolved and checked it, so the mount cannot follow a link that
|
|
183
|
+
// replaced the folder after that check.
|
|
184
|
+
const workspaceSource = opts.workspaceSource || opts.workspacePath;
|
|
185
|
+
if (!isAbsolute(workspaceSource)) {
|
|
186
|
+
throw new Error('wrapArgvWithBwrap opts.workspaceSource must be an absolute path');
|
|
187
|
+
}
|
|
188
|
+
flags.push(opts.workspaceReadOnly ? '--ro-bind' : '--bind', workspaceSource, opts.workspacePath);
|
|
182
189
|
// Entries held read-only inside a writable workspace (its .git). Bound after
|
|
183
190
|
// the workspace so they land on top of it. In a writable workspace a missing
|
|
184
191
|
// entry cannot be protected — the child could create it, and a planted
|
|
@@ -188,8 +195,8 @@ export const wrapArgvWithBwrap = (innerArgv, env, opts = {}) => {
|
|
|
188
195
|
if (!entry || isAbsolute(entry) || entry.split(/[\\/]/).includes('..')) {
|
|
189
196
|
throw new Error('wrapArgvWithBwrap opts.readOnlyWorkspaceEntries entries must be relative names inside the workspace');
|
|
190
197
|
}
|
|
191
|
-
|
|
192
|
-
|
|
198
|
+
flags.push(opts.workspaceReadOnly ? '--ro-bind-try' : '--ro-bind',
|
|
199
|
+
join(workspaceSource, entry), join(opts.workspacePath, entry));
|
|
193
200
|
}
|
|
194
201
|
flags.push('--chdir', opts.workspacePath);
|
|
195
202
|
flags.push('--setenv', 'HOME', opts.homePath || opts.workspacePath);
|
|
@@ -452,6 +452,13 @@ export const buildSeatbeltProfile = ({
|
|
|
452
452
|
// Other seats work in a folder the operator chose, which may be a link on
|
|
453
453
|
// purpose, and leave this unset.
|
|
454
454
|
pinWorkspace = false,
|
|
455
|
+
// The realpath the workspace must still resolve to (F200): a workspace
|
|
456
|
+
// seat's folder as recorded on its first turn (workspace-pin.js). The grant
|
|
457
|
+
// is refused, not moved, when the folder now resolves elsewhere.
|
|
458
|
+
expectedWorkspaceRealpath = null,
|
|
459
|
+
// Folders no rule here may let the jail write, however a grant above is
|
|
460
|
+
// shaped: a workspace seat's own record of its folder (F200).
|
|
461
|
+
denyWritePaths = [],
|
|
455
462
|
}) => {
|
|
456
463
|
for (const [path, label] of [
|
|
457
464
|
[workspacePath, 'workspacePath'],
|
|
@@ -461,6 +468,7 @@ export const buildSeatbeltProfile = ({
|
|
|
461
468
|
assertAbsolutePath(path, label);
|
|
462
469
|
}
|
|
463
470
|
if (mcpConfigDir) assertAbsolutePath(mcpConfigDir, 'mcpConfigDir');
|
|
471
|
+
for (const path of denyWritePaths) assertAbsolutePath(path, 'denyWritePaths entry');
|
|
464
472
|
for (const path of readOnlyPaths) assertAbsolutePath(path, 'readOnlyPaths entry');
|
|
465
473
|
for (const path of readOnlyDirectories) assertAbsolutePath(path, 'readOnlyDirectories entry');
|
|
466
474
|
for (const port of loopbackNetworkPorts) {
|
|
@@ -501,6 +509,13 @@ export const buildSeatbeltProfile = ({
|
|
|
501
509
|
const resolvedWorkspace = workspaceAccess === 'write' && pinWorkspace
|
|
502
510
|
? pinnedRealpath(workspacePath, 'workspace')
|
|
503
511
|
: realpathOrSelf(workspacePath);
|
|
512
|
+
if (expectedWorkspaceRealpath && resolvedWorkspace !== expectedWorkspaceRealpath) {
|
|
513
|
+
throw new Error(
|
|
514
|
+
`refusing a workspace turn: ${workspacePath} now resolves to ${resolvedWorkspace}, `
|
|
515
|
+
+ `not ${expectedWorkspaceRealpath} as it did when the turn was checked. The folder was `
|
|
516
|
+
+ 'replaced during the turn\'s preparation; run the turn again.',
|
|
517
|
+
);
|
|
518
|
+
}
|
|
504
519
|
const resolvedExecutable = realpathOrSelf(executablePath);
|
|
505
520
|
const resolvedState = pinnedRealpath(statePath, 'state folder');
|
|
506
521
|
const resolvedMcpConfig = mcpConfigDir ? realpathOrSelf(mcpConfigDir) : null;
|
|
@@ -576,6 +591,10 @@ export const buildSeatbeltProfile = ({
|
|
|
576
591
|
`(deny file-read* file-write* ${subpath(join(resolvedWorkspace, '.codex'))})`,
|
|
577
592
|
`(deny file-read* file-write* ${envFilesUnder(resolvedWorkspace)})`,
|
|
578
593
|
readOnlyWorkspaceRules,
|
|
594
|
+
// After every allow above, so a workspace that contained one of these
|
|
595
|
+
// folders still could not write it (later rules win).
|
|
596
|
+
[...new Set(denyWritePaths.flatMap((path) => [path, realpathOrSelf(path)]))]
|
|
597
|
+
.map((path) => `(deny file-write* ${subpath(path)})`).join('\n'),
|
|
579
598
|
...claudeRuntimeRules,
|
|
580
599
|
// Later rules win, so this narrows the baseline's same-sandbox allow.
|
|
581
600
|
processInfo === 'self'
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The realpath a workspace-trust seat's folder had when the seat first ran
|
|
3
|
+
* there (F200).
|
|
4
|
+
*
|
|
5
|
+
* A public seat's writable folder is pinned to its own name (seatbelt.js
|
|
6
|
+
* pinnedRealpath, F197). A workspace seat's folder is the operator's choice
|
|
7
|
+
* and may be a link on purpose, so it cannot be pinned that way. But a seat
|
|
8
|
+
* with write access can remove its project folder and leave a link in its
|
|
9
|
+
* place, and the next turn's grant (a Seatbelt subpath on the resolved path,
|
|
10
|
+
* or a bwrap bind of it) would follow that link.
|
|
11
|
+
*
|
|
12
|
+
* So the folder's realpath is recorded the first time the seat runs there,
|
|
13
|
+
* and a later turn whose folder resolves anywhere else is refused before
|
|
14
|
+
* anything is spawned. A link the operator had in place before that first
|
|
15
|
+
* turn is part of what was recorded and keeps working. The record lives in a
|
|
16
|
+
* folder beside the seat's state folder, which no turn is granted: Seatbelt
|
|
17
|
+
* denies writes to it by name, and bwrap never binds it. A workspace that
|
|
18
|
+
* contains it is refused.
|
|
19
|
+
*
|
|
20
|
+
* Each folder has its own record file, created once and never rewritten: a
|
|
21
|
+
* staged copy is hard-linked to the final name, which fails if the name is
|
|
22
|
+
* taken. So two turns recording at once cannot lose each other's record, and
|
|
23
|
+
* two that disagree about one folder cannot both pass.
|
|
24
|
+
*
|
|
25
|
+
* Recording happens on the first turn, not at attach: attach does not know
|
|
26
|
+
* the seat's state folder, and no turn of the seat runs between attach and its
|
|
27
|
+
* first turn. A seat that already ran before this check existed is recorded on
|
|
28
|
+
* its first turn after the update.
|
|
29
|
+
*/
|
|
30
|
+
import {
|
|
31
|
+
link, lstat, mkdir, readFile, realpath, rm, writeFile,
|
|
32
|
+
} from 'fs/promises';
|
|
33
|
+
import { createHash, randomUUID } from 'crypto';
|
|
34
|
+
import {
|
|
35
|
+
basename, dirname, isAbsolute, join, relative, resolve, sep,
|
|
36
|
+
} from 'path';
|
|
37
|
+
|
|
38
|
+
export const workspacePinDir = (statePath) => join(dirname(statePath), 'workspace-pins');
|
|
39
|
+
export const workspacePinFile = (statePath, cwd) => {
|
|
40
|
+
const folder = createHash('sha256').update(resolve(cwd)).digest('hex').slice(0, 16);
|
|
41
|
+
return join(workspacePinDir(statePath), `${basename(statePath)}-${folder}.json`);
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const isInsideOrEqual = (child, parent) => {
|
|
45
|
+
const rel = relative(parent, child);
|
|
46
|
+
return rel === '' || (rel.split(sep)[0] !== '..' && !isAbsolute(rel));
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const readRecord = async (file) => {
|
|
50
|
+
let stat;
|
|
51
|
+
try {
|
|
52
|
+
stat = await lstat(file);
|
|
53
|
+
} catch (err) {
|
|
54
|
+
if (err?.code === 'ENOENT') return null;
|
|
55
|
+
throw err;
|
|
56
|
+
}
|
|
57
|
+
const unreadable = (why) => new Error(
|
|
58
|
+
`refusing a workspace turn: this agent's workspace record ${file} ${why}. `
|
|
59
|
+
+ 'First confirm the agent\'s folder resolves where you expect (for example with `realpath`), '
|
|
60
|
+
+ 'then remove the record; the next turn records the folder as it resolves then.',
|
|
61
|
+
);
|
|
62
|
+
if (!stat.isFile()) throw unreadable('is not a regular file');
|
|
63
|
+
try {
|
|
64
|
+
const parsed = JSON.parse(await readFile(file, 'utf8'));
|
|
65
|
+
if (typeof parsed?.realpath !== 'string' || !parsed.realpath) throw new Error('bad shape');
|
|
66
|
+
return parsed;
|
|
67
|
+
} catch {
|
|
68
|
+
throw unreadable('cannot be read');
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
// True when this call created the record, false when another had already. The
|
|
73
|
+
// final name appears only complete, because it is a link to a finished copy.
|
|
74
|
+
const createRecord = async (file, record, { _writeFile = writeFile } = {}) => {
|
|
75
|
+
await mkdir(dirname(file), { recursive: true, mode: 0o700 });
|
|
76
|
+
const staged = join(dirname(file), `.${basename(file)}.${randomUUID()}.tmp`);
|
|
77
|
+
try {
|
|
78
|
+
await _writeFile(staged, `${JSON.stringify(record, null, 2)}\n`, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
|
|
79
|
+
await link(staged, file);
|
|
80
|
+
return true;
|
|
81
|
+
} catch (err) {
|
|
82
|
+
if (err?.code === 'EEXIST') return false;
|
|
83
|
+
throw err;
|
|
84
|
+
} finally {
|
|
85
|
+
await rm(staged, { force: true });
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
const changed = ({ given, current, recorded, file }) => new Error(
|
|
90
|
+
`refusing a workspace turn: ${given} now resolves to ${current}, but it resolved to `
|
|
91
|
+
+ `${recorded} when this agent first ran there. A turn can replace its folder with a `
|
|
92
|
+
+ 'link, which would let the next turn write wherever the link points. If you moved the '
|
|
93
|
+
+ `project on purpose, remove ${file} (the next turn records the new location), or attach `
|
|
94
|
+
+ 'the agent to the project\'s new folder.',
|
|
95
|
+
);
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Compare the folder's realpath with the one recorded for it, recording it
|
|
99
|
+
* when there is none, and return the realpath to grant. A folder that does not
|
|
100
|
+
* resolve is refused, recorded or not: the run loop makes the folder before
|
|
101
|
+
* each turn, so there is nothing here to grant.
|
|
102
|
+
*
|
|
103
|
+
* `_realpath` and `_writeFile` are test seams.
|
|
104
|
+
*/
|
|
105
|
+
export const holdWorkspaceRealpath = async ({
|
|
106
|
+
cwd, statePath, log = (line) => console.warn(line), _realpath = realpath, _writeFile = writeFile,
|
|
107
|
+
}) => {
|
|
108
|
+
const given = resolve(cwd);
|
|
109
|
+
const file = workspacePinFile(statePath, given);
|
|
110
|
+
let current;
|
|
111
|
+
try {
|
|
112
|
+
current = await _realpath(given);
|
|
113
|
+
} catch {
|
|
114
|
+
// Missing, or a link to nowhere.
|
|
115
|
+
const entry = await readRecord(file);
|
|
116
|
+
if (entry) throw changed({ given, current: 'nothing', recorded: entry.realpath, file });
|
|
117
|
+
throw new Error(
|
|
118
|
+
`refusing a workspace turn: ${given} does not resolve to a folder. `
|
|
119
|
+
+ 'Create the folder or point the agent at one, and run the turn again.',
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
const pinDir = workspacePinDir(statePath);
|
|
123
|
+
let realPinDir = pinDir;
|
|
124
|
+
try {
|
|
125
|
+
realPinDir = await realpath(pinDir);
|
|
126
|
+
} catch {
|
|
127
|
+
try {
|
|
128
|
+
realPinDir = join(await realpath(dirname(pinDir)), basename(pinDir));
|
|
129
|
+
} catch {
|
|
130
|
+
// Neither exists yet; compared as given.
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
if (isInsideOrEqual(realPinDir, current)) {
|
|
134
|
+
throw new Error(
|
|
135
|
+
`refusing a workspace turn: ${given} contains this agent's own record of its folder (${pinDir}), `
|
|
136
|
+
+ 'which the agent must not be able to write. Point the agent at a project folder instead.',
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
const held = async (entry) => {
|
|
140
|
+
if (entry?.realpath !== current) {
|
|
141
|
+
throw changed({ given, current, recorded: entry?.realpath ?? 'nothing', file });
|
|
142
|
+
}
|
|
143
|
+
return current;
|
|
144
|
+
};
|
|
145
|
+
const existing = await readRecord(file);
|
|
146
|
+
if (existing) return held(existing);
|
|
147
|
+
const created = await createRecord(file, {
|
|
148
|
+
workspace: given, realpath: current, recordedAt: new Date().toISOString(),
|
|
149
|
+
}, { _writeFile });
|
|
150
|
+
// Another turn recorded it first: this turn answers to that record.
|
|
151
|
+
if (!created) return held(await readRecord(file));
|
|
152
|
+
// Once per folder: a seat that ran before this check is recorded as its
|
|
153
|
+
// folder resolves now, which the operator should confirm.
|
|
154
|
+
log(`[claude] workspace: recorded ${given} → ${current}`);
|
|
155
|
+
return current;
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
export default { holdWorkspaceRealpath, workspacePinDir, workspacePinFile };
|
package/src/lib/session-store.js
CHANGED
|
@@ -21,13 +21,14 @@
|
|
|
21
21
|
* restart can still suppress a re-delivered event whose ack previously failed.
|
|
22
22
|
*/
|
|
23
23
|
|
|
24
|
-
import { readFileSync, writeFileSync, mkdirSync, existsSync, rmSync } from 'fs';
|
|
24
|
+
import { readFileSync, writeFileSync, mkdirSync, existsSync, rmSync, renameSync } from 'fs';
|
|
25
25
|
import { join } from 'path';
|
|
26
26
|
import { homedir } from 'os';
|
|
27
27
|
|
|
28
28
|
const sessionsDir = () => join(homedir(), '.commonly', 'sessions');
|
|
29
29
|
const sessionsFile = (agentName) => join(sessionsDir(), `${agentName}.json`);
|
|
30
30
|
const handledEventsFile = (agentName) => join(sessionsDir(), `${agentName}.events.json`);
|
|
31
|
+
const noticesFile = (agentName) => join(sessionsDir(), `${agentName}.notices.json`);
|
|
31
32
|
const MAX_HANDLED_EVENTS = 500;
|
|
32
33
|
const handledEventsCache = new Map();
|
|
33
34
|
|
|
@@ -138,10 +139,51 @@ export const recordHandledEvent = (agentName, eventId) => {
|
|
|
138
139
|
handledEventsCache.set(agentName, { ids, set: new Set(ids) });
|
|
139
140
|
};
|
|
140
141
|
|
|
142
|
+
// F178: when the wrapper last posted a rate-limited pod notice, by key, so a
|
|
143
|
+
// notice is not repeated every turn and a restarted seat remembers it.
|
|
144
|
+
// Shape on disk: { "<key>": "<ISO time>" }.
|
|
145
|
+
const readNotices = (agentName) => {
|
|
146
|
+
const file = noticesFile(agentName);
|
|
147
|
+
if (!existsSync(file)) return {};
|
|
148
|
+
try {
|
|
149
|
+
const parsed = JSON.parse(readFileSync(file, 'utf8'));
|
|
150
|
+
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
|
|
151
|
+
} catch {
|
|
152
|
+
return {};
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
/** True when no notice under `key` was recorded within the last `windowMs`. */
|
|
157
|
+
export const noticeDue = (agentName, key, windowMs, now = Date.now()) => {
|
|
158
|
+
if (!agentName || !key) return false;
|
|
159
|
+
const last = Date.parse(readNotices(agentName)[key]);
|
|
160
|
+
return !Number.isFinite(last) || now - last >= windowMs || last > now;
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
export const recordNotice = (agentName, key, now = Date.now()) => {
|
|
164
|
+
if (!agentName || !key) return;
|
|
165
|
+
const state = readNotices(agentName);
|
|
166
|
+
state[key] = new Date(now).toISOString();
|
|
167
|
+
if (!existsSync(sessionsDir())) mkdirSync(sessionsDir(), { recursive: true });
|
|
168
|
+
// Temp file then rename, so a crash mid-write never leaves a torn file, and
|
|
169
|
+
// 0600 because the record says which models this seat's key cannot use.
|
|
170
|
+
const file = noticesFile(agentName);
|
|
171
|
+
const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
|
|
172
|
+
try {
|
|
173
|
+
writeFileSync(tmp, JSON.stringify(state, null, 2), { encoding: 'utf8', mode: 0o600 });
|
|
174
|
+
renameSync(tmp, file);
|
|
175
|
+
} catch (error) {
|
|
176
|
+
rmSync(tmp, { force: true });
|
|
177
|
+
throw error;
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
|
|
141
181
|
export const clearSessions = (agentName) => {
|
|
142
182
|
const file = sessionsFile(agentName);
|
|
143
183
|
if (existsSync(file)) rmSync(file);
|
|
144
184
|
const eventsFile = handledEventsFile(agentName);
|
|
145
185
|
if (existsSync(eventsFile)) rmSync(eventsFile);
|
|
186
|
+
const notices = noticesFile(agentName);
|
|
187
|
+
if (existsSync(notices)) rmSync(notices);
|
|
146
188
|
handledEventsCache.delete(agentName);
|
|
147
189
|
};
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
import { realpathSync } from 'fs';
|
|
18
18
|
import { homedir } from 'os';
|
|
19
19
|
import {
|
|
20
|
-
isAbsolute, join, relative, resolve,
|
|
20
|
+
isAbsolute, join, relative, resolve, sep,
|
|
21
21
|
} from 'path';
|
|
22
22
|
|
|
23
23
|
/** A pod is private only when the server says so in all three fields. */
|
|
@@ -48,7 +48,7 @@ const realOrResolved = (p) => {
|
|
|
48
48
|
|
|
49
49
|
const isInsideOrEqual = (child, parent) => {
|
|
50
50
|
const rel = relative(parent, child);
|
|
51
|
-
return rel === '' || (
|
|
51
|
+
return rel === '' || (rel.split(sep)[0] !== '..' && !isAbsolute(rel));
|
|
52
52
|
};
|
|
53
53
|
|
|
54
54
|
/**
|