dsh-taskbridge 0.0.0-stage → 1.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +754 -0
- package/LICENSE +21 -0
- package/README.md +624 -3
- package/bin/dsh-delegate-codex-agent.js +115 -0
- package/bin/dsh-delegate-control.d.ts +90 -0
- package/bin/dsh-delegate-control.js +450 -0
- package/bin/dsh-delegate-mcp.d.ts +121 -0
- package/bin/dsh-delegate-mcp.js +273 -0
- package/codex/dsh-delegate.toml +245 -0
- package/cordis.patch.yml +6 -0
- package/docs/INTRODUCTION.md +15 -0
- package/docs/INTRODUCTION.zh.md +32 -0
- package/docs/auth-contract.md +138 -0
- package/docs/claude-code.md +31 -0
- package/docs/codex-integration.md +922 -0
- package/docs/contracts-stage-b.md +443 -0
- package/docs/conversation-placement.md +293 -0
- package/docs/plugin-market.md +30 -0
- package/docs/redaction-contract.md +127 -0
- package/docs/runtime-compatibility.md +220 -0
- package/docs/silent-wait.md +191 -0
- package/docs/taskbridge-upgrade.md +28 -0
- package/docs/taskdispatch-upgrade.md +25 -0
- package/docs/worker-permissions.md +347 -0
- package/docs/workspace-contract.md +538 -0
- package/icon.svg +1 -0
- package/lib/client.d.ts +118 -0
- package/lib/client.js +3232 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +135 -4
- package/src/auth/fence.js +361 -0
- package/src/auth/grants.js +789 -0
- package/src/client/api.js +2322 -0
- package/src/client/index.jsx +2333 -0
- package/src/client/styles.js +251 -0
- package/src/codex/installer.js +3260 -0
- package/src/codex/seam.js +429 -0
- package/src/codex/toml.js +784 -0
- package/src/config/defaults.js +164 -0
- package/src/config/redact.js +184 -0
- package/src/config/settings.js +629 -0
- package/src/config/store.js +186 -0
- package/src/config/validate.js +763 -0
- package/src/credentials/seam.js +202 -0
- package/src/http/execution-plane.js +454 -0
- package/src/http/respond.js +175 -0
- package/src/http/user-plane.js +1122 -0
- package/src/index.d.ts +332 -0
- package/src/index.js +657 -0
- package/src/jobs/activity.js +1008 -0
- package/src/jobs/engine.js +3609 -0
- package/src/jobs/history.js +1467 -0
- package/src/mcp/server.js +1820 -0
- package/src/mcp/wait.js +536 -0
- package/src/model/connectivity.js +371 -0
- package/src/model/discovery.js +582 -0
- package/src/model/native-catalog.js +68 -0
- package/src/model/openai-adapter.js +671 -0
- package/src/model/probe.js +264 -0
- package/src/model/providers.js +756 -0
- package/src/model/routing.js +321 -0
- package/src/review/preset.js +868 -0
- package/src/review/prompts.js +126 -0
- package/src/review/reviewer.js +933 -0
- package/src/runtime/agent-runner.js +1738 -0
- package/src/runtime/endpoint-discovery.js +118 -0
- package/src/runtime/permissions.js +1429 -0
- package/src/runtime/sandbox.js +358 -0
- package/src/runtime/session-placement.js +1103 -0
- package/src/workspace/audit.js +775 -0
- package/src/workspace/locks.js +167 -0
- package/src/workspace/preflight.js +424 -0
- package/src/workspace/worktrees.js +613 -0
|
@@ -0,0 +1,1103 @@
|
|
|
1
|
+
// Session placement: which DSH Workspace a delegated run appears in, and which
|
|
2
|
+
// native Session it drives inside that Workspace.
|
|
3
|
+
//
|
|
4
|
+
// There is exactly ONE placement policy, and it is per task, not per directory:
|
|
5
|
+
//
|
|
6
|
+
// * **A new submission is a new conversation.** Every ordinary dispatch creates a
|
|
7
|
+
// fresh DSH Session in the Workspace for its execution directory. Nothing an
|
|
8
|
+
// earlier task did in the same directory can make a new submission continue
|
|
9
|
+
// somebody else's conversation — there is no directory-level mode to read, and
|
|
10
|
+
// a settings document that still stores the legacy `conversation.mode: "reuse"`
|
|
11
|
+
// is accepted as input but is incapable of causing an implicit reuse
|
|
12
|
+
// ({@link LEGACY_CONVERSATION_MODE}).
|
|
13
|
+
//
|
|
14
|
+
// * **A follow-up continues one named task thread.** `continueFromTaskId` names
|
|
15
|
+
// the previous task explicitly, and only that identity is continued: the same
|
|
16
|
+
// Workspace, the same Session. This is why the durable map below is keyed by
|
|
17
|
+
// *task id* rather than by directory — one directory may hold many independent
|
|
18
|
+
// conversations, and only the operator's explicit choice can join them.
|
|
19
|
+
//
|
|
20
|
+
// Two questions, answered by two explicit native APIs and never by a guess:
|
|
21
|
+
//
|
|
22
|
+
// * **Workspace.** A run must be accounted to a real DSH Workspace keyed by the
|
|
23
|
+
// directory it actually executes in (`task.executionPath`) — the worktree when
|
|
24
|
+
// isolation prepared one, the source checkout when it did not.
|
|
25
|
+
// `ctx.workspaceController.create({ path })` creates or reuses that Workspace
|
|
26
|
+
// and returns `{ workspace, created }`.
|
|
27
|
+
//
|
|
28
|
+
// * **Session.** `ctx.sessionController.create({ workspaceId })` creates a new
|
|
29
|
+
// Session in that Workspace; `ctx.sessionController.resolveAgent(sessionId)`
|
|
30
|
+
// returns the live Agent of an existing one, which is what a follow-up drives.
|
|
31
|
+
//
|
|
32
|
+
// Dependencies are named by the service they are: `deps.workspaces` is
|
|
33
|
+
// `ctx.workspaceController` and `deps.sessionController` is `ctx.sessionController`.
|
|
34
|
+
// `deps.sessions` is the native `ctx.sessions` persistence service (used for
|
|
35
|
+
// `flush`, not for planning a Session) and this module never reads it.
|
|
36
|
+
//
|
|
37
|
+
// Both controllers are optional native services. Their absence, or a continuation
|
|
38
|
+
// whose recorded thread can no longer be reached, is a stated refusal
|
|
39
|
+
// ({@link SESSION_CODES}) — never a silent fall back to a new, ungrouped session.
|
|
40
|
+
//
|
|
41
|
+
// What survives a run is deliberately minimal: `{ taskId, sourcePath,
|
|
42
|
+
// executionPath, workspaceId, sessionId, isolation, worktreeId, worktreeState,
|
|
43
|
+
// updatedAt }` per task, in `sessions.json` beside the settings document. No
|
|
44
|
+
// prompt, no transcript, no model output, no credential and no token count is
|
|
45
|
+
// written here. The native session log stays the single owner of conversation
|
|
46
|
+
// content, so this map cannot leak anything it did not receive.
|
|
47
|
+
|
|
48
|
+
import { readFile, rename, rm, writeFile, mkdir } from 'node:fs/promises';
|
|
49
|
+
import { dirname, join } from 'node:path';
|
|
50
|
+
|
|
51
|
+
import { ISOLATION_MODES, SESSIONS_FILE } from '../config/defaults.js';
|
|
52
|
+
import { diagnostic } from '../config/redact.js';
|
|
53
|
+
|
|
54
|
+
/** Stable ids of a managed worktree life cycle, mirrored as a plain string set here. */
|
|
55
|
+
const WORKTREE_STATE_DISPOSED = 'disposed';
|
|
56
|
+
|
|
57
|
+
/** Fields one stored row may carry. Anything else is dropped on the way in. */
|
|
58
|
+
const RECORD_FIELDS = Object.freeze([
|
|
59
|
+
'taskId',
|
|
60
|
+
'sourcePath',
|
|
61
|
+
'executionPath',
|
|
62
|
+
'workspaceId',
|
|
63
|
+
'sessionId',
|
|
64
|
+
'isolation',
|
|
65
|
+
'worktreeId',
|
|
66
|
+
'worktreeState',
|
|
67
|
+
'updatedAt',
|
|
68
|
+
]);
|
|
69
|
+
|
|
70
|
+
/** Session-placement refusal codes. Each one means the run did not start. */
|
|
71
|
+
export const SESSION_CODES = Object.freeze({
|
|
72
|
+
// The native workspaces service is not composed into this harness.
|
|
73
|
+
workspacesUnavailable: 'SESSION_WORKSPACES_UNAVAILABLE',
|
|
74
|
+
// The native session controller is not composed into this harness.
|
|
75
|
+
sessionsUnavailable: 'SESSION_CONTROLLER_UNAVAILABLE',
|
|
76
|
+
// `workspaceController.create` existed but refused or reported nothing usable.
|
|
77
|
+
workspaceRefused: 'SESSION_WORKSPACE_REFUSED',
|
|
78
|
+
// `sessionController.create` existed but refused or reported no session.
|
|
79
|
+
sessionCreateFailed: 'SESSION_CREATE_FAILED',
|
|
80
|
+
// A continuation named a task that this data directory has no identity for.
|
|
81
|
+
// Unknown, stale and never-retained parents are the same operator situation:
|
|
82
|
+
// there is nothing to continue, and nothing is invented in its place.
|
|
83
|
+
continuationUnknown: 'SESSION_CONTINUATION_UNKNOWN',
|
|
84
|
+
// The named parent exists but is not in a state a thread can be continued from
|
|
85
|
+
// (still running, or ended without ever driving a conversation).
|
|
86
|
+
continuationState: 'SESSION_CONTINUATION_STATE',
|
|
87
|
+
// The persisted identity cannot be used to reach a session: no session id, or a
|
|
88
|
+
// worktree identity that is gone or refused.
|
|
89
|
+
continuationUnavailable: 'SESSION_CONTINUATION_UNAVAILABLE',
|
|
90
|
+
// The named parent ran somewhere else than this submission's execution
|
|
91
|
+
// directory. A task chain never crosses directories.
|
|
92
|
+
continuationPathMismatch: 'SESSION_CONTINUATION_PATH_MISMATCH',
|
|
93
|
+
// The recorded Workspace belongs to another source repository.
|
|
94
|
+
continuationWorkspaceMismatch: 'SESSION_CONTINUATION_WORKSPACE_MISMATCH',
|
|
95
|
+
// Continuation was requested and the controller cannot resolve a session at all.
|
|
96
|
+
resumeUnavailable: 'SESSION_RESUME_UNAVAILABLE',
|
|
97
|
+
// The session exists but could not be resolved to a drivable Agent.
|
|
98
|
+
resumeFailed: 'SESSION_RESUME_FAILED',
|
|
99
|
+
// A resolved session's own header names another directory.
|
|
100
|
+
resumePathMismatch: 'SESSION_RESUME_PATH_MISMATCH',
|
|
101
|
+
// The session recorded for the named task no longer exists.
|
|
102
|
+
sessionNotFound: 'SESSION_NOT_FOUND',
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* The conversation mode a stored settings document may still carry.
|
|
107
|
+
*
|
|
108
|
+
* It is accepted so an upgraded document keeps loading, and it is recorded on the
|
|
109
|
+
* legacy boundary only. It has no effect: a new submission is always new, and a
|
|
110
|
+
* follow-up is always the thread named by `continueFromTaskId`. Nothing in this
|
|
111
|
+
* module reads it, which is the property that makes the legacy value incapable of
|
|
112
|
+
* causing an implicit reuse.
|
|
113
|
+
*/
|
|
114
|
+
export const LEGACY_CONVERSATION_MODE = 'reuse';
|
|
115
|
+
|
|
116
|
+
/** Placement outcomes, as reported to an operator. */
|
|
117
|
+
export const PLACEMENT_KINDS = Object.freeze({
|
|
118
|
+
// A fresh DSH Session was created for this run.
|
|
119
|
+
new: 'new',
|
|
120
|
+
// An earlier task's Session was continued.
|
|
121
|
+
continuation: 'continuation',
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
/** Refusal raised by {@link placeSession}. */
|
|
125
|
+
export class SessionPlacementError extends Error {
|
|
126
|
+
/**
|
|
127
|
+
* @param {string} code - stable machine code.
|
|
128
|
+
* @param {string} message - operator-readable explanation.
|
|
129
|
+
* @param {object} [details] - bounded, non-secret context.
|
|
130
|
+
*/
|
|
131
|
+
constructor(code, message, details = {}) {
|
|
132
|
+
super(message);
|
|
133
|
+
this.name = 'SessionPlacementError';
|
|
134
|
+
this.code = code;
|
|
135
|
+
this.details = details;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Canonical form of one directory, as an identity key.
|
|
141
|
+
*
|
|
142
|
+
* The identity of a Workspace is a path string the harness canonicalized once, so
|
|
143
|
+
* this mirrors that spelling and folds case on Windows (NTFS is
|
|
144
|
+
* case-insensitive), exactly as the project-override keys do. Two spellings of
|
|
145
|
+
* one directory therefore address one directory, and two different directories
|
|
146
|
+
* never do.
|
|
147
|
+
* @param {unknown} value - candidate directory path.
|
|
148
|
+
* @returns {string | null} canonical key, or `null` when it is not a path.
|
|
149
|
+
*/
|
|
150
|
+
export function sessionPathKey(value) {
|
|
151
|
+
if (typeof value !== 'string') return null;
|
|
152
|
+
const trimmed = value.trim();
|
|
153
|
+
if (trimmed === '') return null;
|
|
154
|
+
const stripped = trimmed.length > 1 ? trimmed.replace(/[\\/]+$/, '') : trimmed;
|
|
155
|
+
return process.platform === 'win32' ? stripped.toLowerCase() : stripped;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Whether a recorded path is the same canonical path as a current one.
|
|
160
|
+
* @param {unknown} a - first path.
|
|
161
|
+
* @param {unknown} b - second path.
|
|
162
|
+
* @returns {boolean} true when both name one directory.
|
|
163
|
+
*/
|
|
164
|
+
export function sameSessionPath(a, b) {
|
|
165
|
+
const left = sessionPathKey(a);
|
|
166
|
+
const right = sessionPathKey(b);
|
|
167
|
+
return left !== null && right !== null && left === right;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Narrow a dependency object to the two native controllers.
|
|
172
|
+
*
|
|
173
|
+
* Both are read here, once per placement, so every caller sees the same capability
|
|
174
|
+
* decision and a missing service is one refusal code instead of a property read
|
|
175
|
+
* that happens to throw.
|
|
176
|
+
*
|
|
177
|
+
* The two names are not interchangeable and this function is the only place that
|
|
178
|
+
* answers the question, so the mapping is stated once:
|
|
179
|
+
*
|
|
180
|
+
* * `deps.workspaces` — `ctx.workspaceController`;
|
|
181
|
+
* * `deps.sessionController` — `ctx.sessionController`, the service that owns
|
|
182
|
+
* `create`/`resolveAgent`. This is the planner of Sessions.
|
|
183
|
+
*
|
|
184
|
+
* `deps.sessions` is deliberately NOT consulted: that is the native
|
|
185
|
+
* `ctx.sessions` persistence service (the one the runner calls `flush` on), and it
|
|
186
|
+
* has no `create`/`resolveAgent` at all.
|
|
187
|
+
* @param {object} deps - dependency object with optional `workspaces` and `sessionController`.
|
|
188
|
+
* @returns {{ workspaces: object | null, sessions: object | null, worktrees: object | null }} the available services.
|
|
189
|
+
*/
|
|
190
|
+
function controllersOf(deps) {
|
|
191
|
+
const workspaces = controllerOf(deps?.workspaces);
|
|
192
|
+
const sessions = controllerOf(deps?.sessionController);
|
|
193
|
+
const worktrees = controllerOf(deps?.worktrees);
|
|
194
|
+
return {
|
|
195
|
+
// `create` is the capability `ensureWorkspace`/`createWorkspaceSession` need;
|
|
196
|
+
// nothing is placed through a service that cannot create.
|
|
197
|
+
workspaces: typeof workspaces?.create === 'function' ? workspaces : null,
|
|
198
|
+
sessions: typeof sessions?.create === 'function' ? sessions : null,
|
|
199
|
+
// The worktree registry is optional: it exists only to prove that a
|
|
200
|
+
// continuation runs in the tree its parent actually used.
|
|
201
|
+
worktrees: typeof worktrees?.get === 'function' ? worktrees : null,
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* The runtime-resolved accessor for one native controller.
|
|
207
|
+
*
|
|
208
|
+
* A DSH harness may compose `workspaceController` / `sessionController` *after*
|
|
209
|
+
* this plugin activated, or replace one later in the same process. A dependency
|
|
210
|
+
* object that captured `ctx.get(name, false)` once during `apply` fixes the answer
|
|
211
|
+
* at load, so every later run would see `null`. This accessor is deliberately live
|
|
212
|
+
* on both axes: `create` is a getter, and the service is never cached, so what a
|
|
213
|
+
* placement sees is what the harness exposes right now.
|
|
214
|
+
* @param {() => unknown} resolve - reads the current service; may throw or answer null.
|
|
215
|
+
* @param {object} [options] - `onError(error)`: called with a read refusal, which is
|
|
216
|
+
* reported as an absent controller.
|
|
217
|
+
* @returns {{ readonly current: object | null }} accessor; `null` means absent.
|
|
218
|
+
*/
|
|
219
|
+
export function liveControllerAccessor(resolve, options = {}) {
|
|
220
|
+
const onError = typeof options?.onError === 'function' ? options.onError : null;
|
|
221
|
+
return {
|
|
222
|
+
/**
|
|
223
|
+
* The service as it is NOW, or null when the harness does not expose it.
|
|
224
|
+
* @returns {object | null} live service.
|
|
225
|
+
*/
|
|
226
|
+
get current() {
|
|
227
|
+
try {
|
|
228
|
+
const service = resolve();
|
|
229
|
+
return service === undefined || service === null ? null : service;
|
|
230
|
+
} catch (error) {
|
|
231
|
+
// An unreadable service is an absent service for placement purposes: the
|
|
232
|
+
// caller then refuses with `SESSION_*_UNAVAILABLE` instead of surfacing a
|
|
233
|
+
// property-access error as an execution failure.
|
|
234
|
+
onError?.(error);
|
|
235
|
+
return null;
|
|
236
|
+
}
|
|
237
|
+
},
|
|
238
|
+
get create() {
|
|
239
|
+
const service = this.current;
|
|
240
|
+
const method = service?.create;
|
|
241
|
+
// Bound to the LIVE service, so a caller reading `create` calls through the
|
|
242
|
+
// service this instant rather than through an object it saw before.
|
|
243
|
+
return typeof method === 'function' ? method.bind(service) : null;
|
|
244
|
+
},
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Read one controller off a dependency value, following an accessor when it is one.
|
|
250
|
+
* @param {unknown} value - a controller, an accessor, or nothing.
|
|
251
|
+
* @returns {object | null} the service as it is now, or null.
|
|
252
|
+
*/
|
|
253
|
+
function controllerOf(value) {
|
|
254
|
+
if (value === undefined || value === null) return null;
|
|
255
|
+
// An accessor is the only dependency value that carries a live `current`
|
|
256
|
+
// member; the services themselves never do.
|
|
257
|
+
if (typeof value === 'object' && 'current' in value) {
|
|
258
|
+
const live = value.current;
|
|
259
|
+
return live === null || live === undefined ? null : live;
|
|
260
|
+
}
|
|
261
|
+
return value;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Normalize a requested continuation identity, or `null` when none was asked for.
|
|
266
|
+
*
|
|
267
|
+
* An absent, blank or non-string value means "this is a new submission". A blank
|
|
268
|
+
* string is deliberately treated as absent rather than as a refusal: it is what an
|
|
269
|
+
* MCP client sends for "no value", and refusing it would turn "start a new
|
|
270
|
+
* conversation" into an error.
|
|
271
|
+
* @param {unknown} value - caller-supplied `continueFromTaskId`.
|
|
272
|
+
* @returns {string | null} the task id to continue, or null.
|
|
273
|
+
*/
|
|
274
|
+
export function continuationOf(value) {
|
|
275
|
+
if (typeof value !== 'string') return null;
|
|
276
|
+
const trimmed = value.trim();
|
|
277
|
+
return trimmed === '' ? null : trimmed;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* Resolve the native Workspace a delegated run belongs to.
|
|
282
|
+
*
|
|
283
|
+
* `workspaceController.create({ path })` creates the Workspace for an existing
|
|
284
|
+
* directory or returns the one that already owns it (`created: false`).
|
|
285
|
+
* @param {object} workspaces - the native Workspace controller.
|
|
286
|
+
* @param {string} path - the directory the run executes in.
|
|
287
|
+
* @returns {Promise<{ workspaceId: string, path: string, created: boolean }>} the Workspace fact.
|
|
288
|
+
* @throws {SessionPlacementError} when the controller refuses or reports nothing usable.
|
|
289
|
+
*/
|
|
290
|
+
export async function ensureWorkspace(workspaces, path) {
|
|
291
|
+
let value;
|
|
292
|
+
try {
|
|
293
|
+
value = await workspaces.create({ path });
|
|
294
|
+
} catch (error) {
|
|
295
|
+
throw new SessionPlacementError(
|
|
296
|
+
SESSION_CODES.workspaceRefused,
|
|
297
|
+
'DSH refused to group this run into a Workspace for its execution directory',
|
|
298
|
+
{ cause: typeof error?.code === 'string' ? error.code : null, detail: diagnostic(error?.message ?? error, 200) },
|
|
299
|
+
);
|
|
300
|
+
}
|
|
301
|
+
const workspace = value?.workspace ?? null;
|
|
302
|
+
const workspaceId = workspace?.workspaceId ?? null;
|
|
303
|
+
if (typeof workspaceId !== 'string' || workspaceId === '') {
|
|
304
|
+
// Fail closed: a run without a Workspace is the unpartitioned state this
|
|
305
|
+
// feature exists to remove, so an unusable answer may not become a session.
|
|
306
|
+
throw new SessionPlacementError(
|
|
307
|
+
SESSION_CODES.workspaceRefused,
|
|
308
|
+
'the Workspace controller returned no Workspace identity for this directory',
|
|
309
|
+
{ returned: value === null || typeof value !== 'object' ? typeof value : 'object without workspace.workspaceId' },
|
|
310
|
+
);
|
|
311
|
+
}
|
|
312
|
+
return {
|
|
313
|
+
workspaceId,
|
|
314
|
+
path: typeof workspace.path === 'string' && workspace.path !== '' ? workspace.path : path,
|
|
315
|
+
created: value?.created === true,
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* Place one run: a new Session, or the explicit continuation of one task thread.
|
|
321
|
+
*
|
|
322
|
+
* The decision is made here and only here, from two facts the caller supplies:
|
|
323
|
+
*
|
|
324
|
+
* 1. **capability checks first** — no Session is created and no Agent resolved
|
|
325
|
+
* before it is known that the run can be driven at all, so a refusal never
|
|
326
|
+
* leaves a Session behind;
|
|
327
|
+
* 2. **`continueFromTaskId` omitted** — a fresh Session is created in the
|
|
328
|
+
* Workspace for this run's execution directory, then resolved to a live Agent.
|
|
329
|
+
* Nothing is read from the identity map: a new submission is new even when the
|
|
330
|
+
* same directory has a long history, which is the property the removed
|
|
331
|
+
* directory-level `reuse` setting used to violate;
|
|
332
|
+
* 3. **`continueFromTaskId` supplied** — the recorded identity of *that task* is
|
|
333
|
+
* loaded and every fact a thread continuation depends on is re-checked
|
|
334
|
+
* ({@link validateContinuation}). A continuation that cannot be honoured is a
|
|
335
|
+
* refusal; it is never quietly replaced by the new-Session path, because that
|
|
336
|
+
* would report a continued conversation the operator is not actually in.
|
|
337
|
+
*
|
|
338
|
+
* Both paths return a live `agent`, and neither creates a Session or an Agent
|
|
339
|
+
* twice.
|
|
340
|
+
* @param {object} deps - dependency object with `workspaces`, `sessionController`,
|
|
341
|
+
* `sessionStore`, optional `worktrees`, and the task/connection facts a
|
|
342
|
+
* continuation must match (`taskId`, `connectionId`, `sourcePath`).
|
|
343
|
+
* @param {object} request - `path` (the actual execution directory), `presetId`,
|
|
344
|
+
* and optional `continueFromTaskId`.
|
|
345
|
+
* @returns {Promise<object>} placement fact: kind, Workspace, Session, Agent and
|
|
346
|
+
* the continuation facts.
|
|
347
|
+
* @throws {SessionPlacementError} when the run cannot be placed.
|
|
348
|
+
*/
|
|
349
|
+
export async function placeSession(deps, request) {
|
|
350
|
+
const { workspaces, sessions } = controllersOf(deps);
|
|
351
|
+
if (workspaces === null) {
|
|
352
|
+
throw new SessionPlacementError(
|
|
353
|
+
SESSION_CODES.workspacesUnavailable,
|
|
354
|
+
'the DSH Workspace controller is unavailable, so this run could not be grouped into a Workspace',
|
|
355
|
+
{},
|
|
356
|
+
);
|
|
357
|
+
}
|
|
358
|
+
if (sessions === null) {
|
|
359
|
+
throw new SessionPlacementError(
|
|
360
|
+
SESSION_CODES.sessionsUnavailable,
|
|
361
|
+
'the DSH session controller is unavailable, so no Workspace-scoped session could be created',
|
|
362
|
+
{},
|
|
363
|
+
);
|
|
364
|
+
}
|
|
365
|
+
const path = sessionPathKey(request?.path);
|
|
366
|
+
if (path === null) {
|
|
367
|
+
throw new SessionPlacementError(SESSION_CODES.sessionCreateFailed, 'no execution directory was resolved for this run', {});
|
|
368
|
+
}
|
|
369
|
+
const execPath = request.path;
|
|
370
|
+
const continueFromTaskId = continuationOf(request?.continueFromTaskId);
|
|
371
|
+
|
|
372
|
+
const workspace = await ensureWorkspace(workspaces, execPath);
|
|
373
|
+
|
|
374
|
+
if (continueFromTaskId !== null) {
|
|
375
|
+
const parent = await loadContinuation(deps, continueFromTaskId);
|
|
376
|
+
const resumed = await continueTaskThread({
|
|
377
|
+
deps,
|
|
378
|
+
sessions,
|
|
379
|
+
workspace,
|
|
380
|
+
parent,
|
|
381
|
+
execPath,
|
|
382
|
+
presetId: request?.presetId,
|
|
383
|
+
});
|
|
384
|
+
return {
|
|
385
|
+
kind: PLACEMENT_KINDS.continuation,
|
|
386
|
+
continuedFromTaskId: continueFromTaskId,
|
|
387
|
+
reused: true,
|
|
388
|
+
workspaceId: workspace.workspaceId,
|
|
389
|
+
workspacePath: workspace.path,
|
|
390
|
+
workspaceCreated: workspace.created,
|
|
391
|
+
sessionId: resumed.sessionId,
|
|
392
|
+
sessionCreated: false,
|
|
393
|
+
agent: resumed.agent,
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
const sessionId = await createWorkspaceSession(sessions, workspace.workspaceId, request?.presetId);
|
|
398
|
+
// A freshly created Session is joined to its Agent by resolving it, through the
|
|
399
|
+
// same call a continuation uses. Nothing else attaches an Agent to a Session
|
|
400
|
+
// that the caller did not create through `agents.create`, and `agents.create`
|
|
401
|
+
// cannot be used here: it would create a SECOND Session under the id it is handed.
|
|
402
|
+
const created = await attachWorkspaceAgent({ sessions, workspace, sessionId, execPath });
|
|
403
|
+
return {
|
|
404
|
+
kind: PLACEMENT_KINDS.new,
|
|
405
|
+
continuedFromTaskId: null,
|
|
406
|
+
reused: false,
|
|
407
|
+
workspaceId: workspace.workspaceId,
|
|
408
|
+
workspacePath: workspace.path,
|
|
409
|
+
workspaceCreated: workspace.created,
|
|
410
|
+
sessionId: created.sessionId,
|
|
411
|
+
sessionCreated: true,
|
|
412
|
+
agent: created.agent,
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* Create one new Session inside a Workspace.
|
|
418
|
+
*
|
|
419
|
+
* `workspaceId` is passed instead of `cwd` on purpose: the native controller
|
|
420
|
+
* derives the Session's directory from the Workspace, which is the same canonical
|
|
421
|
+
* path membership is validated against. Passing both is refused by the controller.
|
|
422
|
+
* @param {object} sessions - the native session controller.
|
|
423
|
+
* @param {string} workspaceId - Workspace identity.
|
|
424
|
+
* @param {string | undefined} presetId - agent preset the Session must own, if any.
|
|
425
|
+
* @returns {Promise<string>} the created Session's id.
|
|
426
|
+
* @throws {SessionPlacementError} when the controller refuses or reports none.
|
|
427
|
+
*/
|
|
428
|
+
async function createWorkspaceSession(sessions, workspaceId, presetId) {
|
|
429
|
+
let value;
|
|
430
|
+
try {
|
|
431
|
+
value = await sessions.create({
|
|
432
|
+
workspaceId,
|
|
433
|
+
...(typeof presetId === 'string' && presetId !== '' ? { agentPreset: presetId } : {}),
|
|
434
|
+
});
|
|
435
|
+
} catch (error) {
|
|
436
|
+
throw new SessionPlacementError(
|
|
437
|
+
SESSION_CODES.sessionCreateFailed,
|
|
438
|
+
'DSH could not create a session in the Workspace for this run',
|
|
439
|
+
{ cause: typeof error?.code === 'string' ? error.code : null, detail: diagnostic(error?.message ?? error, 200) },
|
|
440
|
+
);
|
|
441
|
+
}
|
|
442
|
+
const sessionId = value?.sessionId ?? null;
|
|
443
|
+
if (typeof sessionId !== 'string' || sessionId === '') {
|
|
444
|
+
throw new SessionPlacementError(
|
|
445
|
+
SESSION_CODES.sessionCreateFailed,
|
|
446
|
+
'the session controller returned no session identity for this run',
|
|
447
|
+
{},
|
|
448
|
+
);
|
|
449
|
+
}
|
|
450
|
+
return sessionId;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* Read the persisted identity of one parent task, or refuse.
|
|
455
|
+
*
|
|
456
|
+
* Unknown, stale, pruned and never-recorded parents are one refusal code
|
|
457
|
+
* (`SESSION_CONTINUATION_UNKNOWN`) because they are one operator situation: the
|
|
458
|
+
* named thread does not exist here, so there is nothing to continue. A continuation
|
|
459
|
+
* is never widened to "some other task in this directory".
|
|
460
|
+
* @param {object} deps - dependency object.
|
|
461
|
+
* @param {string} taskId - the task id the caller named.
|
|
462
|
+
* @returns {Promise<object>} the stored identity.
|
|
463
|
+
* @throws {SessionPlacementError} when no identity exists for that task.
|
|
464
|
+
*/
|
|
465
|
+
async function loadContinuation(deps, taskId) {
|
|
466
|
+
const store = deps?.sessionStore ?? null;
|
|
467
|
+
// A task this process still holds is judged by the engine's own record, which is
|
|
468
|
+
// strictly more informative than the persisted row: liveness, connection
|
|
469
|
+
// ownership and "did it ever drive a conversation" are all live facts there. The
|
|
470
|
+
// engine reports the refusal itself and returns here only when the parent is not
|
|
471
|
+
// one of its own, so this check cannot hide an unknown id.
|
|
472
|
+
if (typeof deps?.assertAdmissible === 'function') {
|
|
473
|
+
deps.assertAdmissible(taskId);
|
|
474
|
+
}
|
|
475
|
+
if (store === null || store === undefined || typeof store.get !== 'function') {
|
|
476
|
+
throw new SessionPlacementError(
|
|
477
|
+
SESSION_CODES.continuationUnavailable,
|
|
478
|
+
'this deployment keeps no task-to-conversation identity, so the named task cannot be continued',
|
|
479
|
+
{ continueFromTaskId: taskId, reason: 'no session identity store' },
|
|
480
|
+
);
|
|
481
|
+
}
|
|
482
|
+
let record;
|
|
483
|
+
try {
|
|
484
|
+
record = await store.get(taskId);
|
|
485
|
+
} catch (error) {
|
|
486
|
+
throw new SessionPlacementError(
|
|
487
|
+
SESSION_CODES.continuationUnavailable,
|
|
488
|
+
'the stored task-to-conversation identity could not be read, so the named task cannot be continued',
|
|
489
|
+
{ continueFromTaskId: taskId, detail: diagnostic(error?.message ?? error, 200) },
|
|
490
|
+
);
|
|
491
|
+
}
|
|
492
|
+
if (record === null || record === undefined || typeof record !== 'object') {
|
|
493
|
+
throw new SessionPlacementError(
|
|
494
|
+
SESSION_CODES.continuationUnknown,
|
|
495
|
+
'no conversation is recorded for the named task, so it cannot be continued',
|
|
496
|
+
{
|
|
497
|
+
continueFromTaskId: taskId,
|
|
498
|
+
reason: 'unknown, pruned or started by another deployment',
|
|
499
|
+
hint: 'omit continueFromTaskId to start a new task conversation',
|
|
500
|
+
},
|
|
501
|
+
);
|
|
502
|
+
}
|
|
503
|
+
return record;
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/**
|
|
507
|
+
* Validate one continuation and resolve the parent thread's live Agent.
|
|
508
|
+
*
|
|
509
|
+
* Every guard below is a *refusal*, never a repair, because each of them names a
|
|
510
|
+
* case in which continuing would silently join the wrong conversation:
|
|
511
|
+
*
|
|
512
|
+
* 1. the recorded identity must name a session at all;
|
|
513
|
+
* 2. the parent must have run in exactly this run's execution directory — a chain
|
|
514
|
+
* never crosses directories, and a plugin-managed worktree is a different
|
|
515
|
+
* directory from its source on purpose;
|
|
516
|
+
* 3. the parent must have run for the same source repository: the recorded
|
|
517
|
+
* Workspace path must be that repository;
|
|
518
|
+
* 4. a worktree parent must still be a live managed tree whose recorded
|
|
519
|
+
* `worktreeId` matches, because that tree is where the earlier uncommitted
|
|
520
|
+
* worker changes are;
|
|
521
|
+
* 5. the native controller must be able to resolve the session, and the resolved
|
|
522
|
+
* Agent's own header must name the same directory.
|
|
523
|
+
*
|
|
524
|
+
* The ownership facts checked here are the ones that are knowable from the record
|
|
525
|
+
* and the native services. Connection ownership is enforced before placement, where
|
|
526
|
+
* the engine still holds the connection identity: this module never sees one.
|
|
527
|
+
* @param {object} request - `deps`, `sessions`, `workspace`, `parent`, `execPath`, `presetId`.
|
|
528
|
+
* @returns {Promise<{ sessionId: string, agent: object }>} the live Agent of the continued thread.
|
|
529
|
+
* @throws {SessionPlacementError} when the thread cannot be continued.
|
|
530
|
+
*/
|
|
531
|
+
async function continueTaskThread({ deps, sessions, workspace, parent, execPath, presetId }) {
|
|
532
|
+
const parentTaskId = parent.taskId ?? null;
|
|
533
|
+
const sessionId = typeof parent.sessionId === 'string' ? parent.sessionId.trim() : '';
|
|
534
|
+
if (sessionId === '') {
|
|
535
|
+
throw new SessionPlacementError(
|
|
536
|
+
SESSION_CODES.continuationUnavailable,
|
|
537
|
+
'the named task drove no conversation, so there is no thread to continue',
|
|
538
|
+
{ continueFromTaskId: parentTaskId, reason: 'no recorded session' },
|
|
539
|
+
);
|
|
540
|
+
}
|
|
541
|
+
const recordedExec = parent.executionPath ?? parent.path ?? null;
|
|
542
|
+
if (!sameSessionPath(recordedExec, execPath)) {
|
|
543
|
+
throw new SessionPlacementError(
|
|
544
|
+
SESSION_CODES.continuationPathMismatch,
|
|
545
|
+
'the named task ran in another execution directory, so its conversation was not continued',
|
|
546
|
+
{
|
|
547
|
+
continueFromTaskId: parentTaskId,
|
|
548
|
+
recordedExecutionPath: typeof recordedExec === 'string' ? recordedExec : null,
|
|
549
|
+
executionPath: execPath,
|
|
550
|
+
hint: 'a follow-up must run where its task ran; a plugin-managed worktree is its own directory',
|
|
551
|
+
},
|
|
552
|
+
);
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
const isolation = parent.isolation ?? null;
|
|
556
|
+
if (isolation === 'worktree') {
|
|
557
|
+
assertWorktreeContinuable(deps, parent, execPath);
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
const recordedSource = parent.sourcePath ?? null;
|
|
561
|
+
const currentSource = deps?.sourcePath ?? null;
|
|
562
|
+
if (typeof recordedSource === 'string' && recordedSource !== '' && typeof currentSource === 'string' && currentSource !== ''
|
|
563
|
+
&& !sameSessionPath(recordedSource, currentSource)) {
|
|
564
|
+
throw new SessionPlacementError(
|
|
565
|
+
SESSION_CODES.continuationWorkspaceMismatch,
|
|
566
|
+
'the named task was authorized for another source repository, so its conversation was not continued',
|
|
567
|
+
{
|
|
568
|
+
continueFromTaskId: parentTaskId,
|
|
569
|
+
reason: 'different source repository',
|
|
570
|
+
},
|
|
571
|
+
);
|
|
572
|
+
}
|
|
573
|
+
if (typeof parent.workspaceId === 'string' && parent.workspaceId !== ''
|
|
574
|
+
&& parent.workspaceId !== workspace.workspaceId) {
|
|
575
|
+
// The Workspace is keyed by the execution directory: reaching a Workspace from
|
|
576
|
+
// another directory would be a cross-directory continuation by another name.
|
|
577
|
+
throw new SessionPlacementError(
|
|
578
|
+
SESSION_CODES.continuationWorkspaceMismatch,
|
|
579
|
+
'the named task belongs to another DSH Workspace, so its conversation was not continued',
|
|
580
|
+
{
|
|
581
|
+
continueFromTaskId: parentTaskId,
|
|
582
|
+
reason: 'different workspace',
|
|
583
|
+
},
|
|
584
|
+
);
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
const resolved = await resumeExistingSession({ sessions, workspace, sessionId, execPath, presetId, parentTaskId });
|
|
588
|
+
return resolved;
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/**
|
|
592
|
+
* Prove that a worktree parent is still the tree this continuation must reuse.
|
|
593
|
+
*
|
|
594
|
+
* The follow-up has to run in the tree the parent executed in, because that is
|
|
595
|
+
* where the parent's uncommitted changes are. Creating a fresh tree would start
|
|
596
|
+
* from a clean commit and silently hide them, so a tree that is gone, disposed, or
|
|
597
|
+
* no longer the one the record names is a refusal.
|
|
598
|
+
* @param {object} deps - dependency object with the optional `worktrees` registry.
|
|
599
|
+
* @param {object} parent - recorded identity of the parent task.
|
|
600
|
+
* @param {string} execPath - the execution directory this continuation resolved.
|
|
601
|
+
* @returns {void}
|
|
602
|
+
* @throws {SessionPlacementError} when the tree cannot be reused.
|
|
603
|
+
*/
|
|
604
|
+
function assertWorktreeContinuable(deps, parent, execPath) {
|
|
605
|
+
const taskId = parent.taskId ?? null;
|
|
606
|
+
const worktreeId = typeof parent.worktreeId === 'string' ? parent.worktreeId.trim() : '';
|
|
607
|
+
if (worktreeId === '') {
|
|
608
|
+
throw new SessionPlacementError(
|
|
609
|
+
SESSION_CODES.continuationUnavailable,
|
|
610
|
+
'the named task ran in an isolated tree whose identity was not recorded, so it cannot be reused safely',
|
|
611
|
+
{ continueFromTaskId: taskId, reason: 'no recorded worktree identity' },
|
|
612
|
+
);
|
|
613
|
+
}
|
|
614
|
+
if (parent.worktreeState === WORKTREE_STATE_DISPOSED) {
|
|
615
|
+
throw new SessionPlacementError(
|
|
616
|
+
SESSION_CODES.continuationUnavailable,
|
|
617
|
+
'the isolated tree the named task ran in has been removed, so the thread cannot be continued',
|
|
618
|
+
{ continueFromTaskId: taskId, reason: 'worktree disposed' },
|
|
619
|
+
);
|
|
620
|
+
}
|
|
621
|
+
const registry = deps?.worktrees ?? null;
|
|
622
|
+
if (registry === null || registry === undefined || typeof registry.get !== 'function') {
|
|
623
|
+
throw new SessionPlacementError(
|
|
624
|
+
SESSION_CODES.continuationUnavailable,
|
|
625
|
+
'this harness cannot report its managed trees, so the named task\'s tree cannot be proven reusable',
|
|
626
|
+
{ continueFromTaskId: taskId, reason: 'no worktree registry' },
|
|
627
|
+
);
|
|
628
|
+
}
|
|
629
|
+
let tree;
|
|
630
|
+
try {
|
|
631
|
+
tree = registry.get(execPath);
|
|
632
|
+
} catch (error) {
|
|
633
|
+
throw new SessionPlacementError(
|
|
634
|
+
SESSION_CODES.continuationUnavailable,
|
|
635
|
+
'this harness refused to report the named task\'s tree, so the thread cannot be continued',
|
|
636
|
+
{ continueFromTaskId: taskId, detail: diagnostic(error?.message ?? error, 200) },
|
|
637
|
+
);
|
|
638
|
+
}
|
|
639
|
+
if (tree === null || tree === undefined || typeof tree !== 'object') {
|
|
640
|
+
throw new SessionPlacementError(
|
|
641
|
+
SESSION_CODES.continuationUnavailable,
|
|
642
|
+
'no managed tree exists at the named task\'s execution path, so the thread cannot be continued',
|
|
643
|
+
{ continueFromTaskId: taskId, reason: 'tree not managed here' },
|
|
644
|
+
);
|
|
645
|
+
}
|
|
646
|
+
if (tree.state === WORKTREE_STATE_DISPOSED) {
|
|
647
|
+
throw new SessionPlacementError(
|
|
648
|
+
SESSION_CODES.continuationUnavailable,
|
|
649
|
+
'the isolated tree the named task ran in has been removed, so the thread cannot be continued',
|
|
650
|
+
{ continueFromTaskId: taskId, reason: 'worktree disposed' },
|
|
651
|
+
);
|
|
652
|
+
}
|
|
653
|
+
const foundId = typeof tree.worktreeId === 'string' && tree.worktreeId !== '' ? tree.worktreeId : (tree.taskId ?? null);
|
|
654
|
+
if (typeof foundId === 'string' && foundId !== '' && !sameWorktreeId(foundId, worktreeId)) {
|
|
655
|
+
throw new SessionPlacementError(
|
|
656
|
+
SESSION_CODES.continuationUnavailable,
|
|
657
|
+
'the tree at the named task\'s execution path belongs to another run, so it was not reused',
|
|
658
|
+
{ continueFromTaskId: taskId, reason: 'worktree identity mismatch' },
|
|
659
|
+
);
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
/**
|
|
664
|
+
* Whether two worktree identities name one tree.
|
|
665
|
+
*
|
|
666
|
+
* The registry historically exposes the tree's own `taskId` (the id of the task
|
|
667
|
+
* that prepared it) and a `worktreeId` in newer views, so both spellings are
|
|
668
|
+
* compared the way a path is compared: exactly, then case-folded on Windows.
|
|
669
|
+
* @param {string} a - first identity.
|
|
670
|
+
* @param {string} b - second identity.
|
|
671
|
+
* @returns {boolean} true when both name one tree.
|
|
672
|
+
*/
|
|
673
|
+
export function sameWorktreeId(a, b) {
|
|
674
|
+
if (typeof a !== 'string' || typeof b !== 'string') return false;
|
|
675
|
+
if (a === b) return true;
|
|
676
|
+
return process.platform === 'win32' && a.toLowerCase() === b.toLowerCase();
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
/**
|
|
680
|
+
* Resolve an existing Session to the live, drivable Agent a continuation drives.
|
|
681
|
+
*
|
|
682
|
+
* `sessionController.resolveAgent(sessionId)` is the only documented way to reach
|
|
683
|
+
* the Agent of a Session the caller did not create through `agents.create`, and
|
|
684
|
+
* driving the resolved Agent (rather than its logged header) is what makes the
|
|
685
|
+
* turn land in the SAME native session log.
|
|
686
|
+
* @param {object} request - `sessions`, `workspace`, `sessionId`, `execPath`, `presetId`, `parentTaskId`.
|
|
687
|
+
* @returns {Promise<{ sessionId: string, agent: object }>} the live Agent and its id.
|
|
688
|
+
* @throws {SessionPlacementError} when no drivable Agent can be resolved.
|
|
689
|
+
*/
|
|
690
|
+
async function resumeExistingSession({ sessions, workspace, sessionId, execPath, presetId, parentTaskId }) {
|
|
691
|
+
if (typeof sessions.resolveAgent !== 'function') {
|
|
692
|
+
throw new SessionPlacementError(
|
|
693
|
+
SESSION_CODES.resumeUnavailable,
|
|
694
|
+
'this DSH build cannot resolve an existing session, so the follow-up cannot be continued',
|
|
695
|
+
{ reason: 'sessionController.resolveAgent is missing', continueFromTaskId: parentTaskId ?? null },
|
|
696
|
+
);
|
|
697
|
+
}
|
|
698
|
+
return await attachWorkspaceAgent({
|
|
699
|
+
sessions,
|
|
700
|
+
workspace,
|
|
701
|
+
sessionId,
|
|
702
|
+
execPath,
|
|
703
|
+
presetId,
|
|
704
|
+
parentTaskId,
|
|
705
|
+
failureCode: SESSION_CODES.resumeFailed,
|
|
706
|
+
});
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
/**
|
|
710
|
+
* Resolve one existing Session to the live Agent this run will drive.
|
|
711
|
+
*
|
|
712
|
+
* The same call serves both paths, which is deliberate:
|
|
713
|
+
*
|
|
714
|
+
* * for a continuation it continues the recorded conversation;
|
|
715
|
+
* * for a new submission it attaches the Agent to the Session that was just
|
|
716
|
+
* created in the Workspace, instead of creating a second one.
|
|
717
|
+
*
|
|
718
|
+
* Nothing here creates a Session or an Agent; a Session that was created but whose
|
|
719
|
+
* Agent cannot be resolved is refused. The alternative — driving an Agent that is
|
|
720
|
+
* not attached to the placed Session — would report a Workspace grouping the run
|
|
721
|
+
* did not actually have.
|
|
722
|
+
* @param {object} request - `sessions`, `workspace`, `sessionId`, `execPath`, `presetId`,
|
|
723
|
+
* optional `parentTaskId`, optional `failureCode`.
|
|
724
|
+
* @returns {Promise<{ sessionId: string, agent: object }>} the live Agent and its id.
|
|
725
|
+
* @throws {SessionPlacementError} when no drivable Agent can be resolved.
|
|
726
|
+
*/
|
|
727
|
+
async function attachWorkspaceAgent({ sessions, workspace, sessionId, execPath, presetId, parentTaskId = null, failureCode = null }) {
|
|
728
|
+
if (typeof sessions.resolveAgent !== 'function') {
|
|
729
|
+
throw new SessionPlacementError(
|
|
730
|
+
SESSION_CODES.resumeUnavailable,
|
|
731
|
+
'this DSH build cannot resolve a session to a drivable agent, so the run was not started',
|
|
732
|
+
{ reason: 'sessionController.resolveAgent is missing', presetId: presetId ?? null },
|
|
733
|
+
);
|
|
734
|
+
}
|
|
735
|
+
let found;
|
|
736
|
+
try {
|
|
737
|
+
found = await sessions.resolveAgent(sessionId);
|
|
738
|
+
} catch (error) {
|
|
739
|
+
throw resumeFailure(workspace, error, parentTaskId, failureCode);
|
|
740
|
+
}
|
|
741
|
+
if (found === null || typeof found !== 'object' || found.error !== undefined) {
|
|
742
|
+
throw resumeFailure(workspace, found?.error ?? { message: 'no agent was returned' }, parentTaskId, failureCode);
|
|
743
|
+
}
|
|
744
|
+
const agent = found.agent ?? null;
|
|
745
|
+
if (agent === null || typeof agent !== 'object' || typeof agent.whenIdle !== 'function'
|
|
746
|
+
|| typeof agent.followup !== 'function') {
|
|
747
|
+
throw new SessionPlacementError(
|
|
748
|
+
failureCode ?? SESSION_CODES.resumeFailed,
|
|
749
|
+
'the resolved session did not yield a drivable agent, so the run was not started',
|
|
750
|
+
{ code: 'SESSION_NOT_DRIVABLE', continueFromTaskId: parentTaskId },
|
|
751
|
+
);
|
|
752
|
+
}
|
|
753
|
+
const headerCwd = agent.session?.header?.cwd ?? null;
|
|
754
|
+
if (typeof headerCwd === 'string' && headerCwd !== '' && !sameSessionPath(headerCwd, execPath)) {
|
|
755
|
+
throw new SessionPlacementError(
|
|
756
|
+
SESSION_CODES.resumePathMismatch,
|
|
757
|
+
'the resolved session runs in another directory, so it was refused',
|
|
758
|
+
{ sessionPath: headerCwd, executionPath: execPath, continueFromTaskId: parentTaskId },
|
|
759
|
+
);
|
|
760
|
+
}
|
|
761
|
+
return { sessionId: agent.session?.id ?? sessionId, agent };
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
/**
|
|
765
|
+
* Shape one resume failure into the bounded refusal the engine reports.
|
|
766
|
+
*
|
|
767
|
+
* The native codes an operator can act on are preserved (`session/not-found`,
|
|
768
|
+
* `session/writer-held`), and the recorded identity is dropped from the
|
|
769
|
+
* diagnostic, which also keeps the report free of a resumable handle.
|
|
770
|
+
* @param {object} workspace - Workspace fact.
|
|
771
|
+
* @param {unknown} error - whatever the controller answered with.
|
|
772
|
+
* @param {string | null} parentTaskId - the task whose thread was being continued.
|
|
773
|
+
* @param {string | null} failureCode - the placement code to report.
|
|
774
|
+
* @returns {SessionPlacementError} refusal.
|
|
775
|
+
*/
|
|
776
|
+
function resumeFailure(workspace, error, parentTaskId = null, failureCode = null) {
|
|
777
|
+
const code = typeof error?.code === 'string' ? error.code : null;
|
|
778
|
+
const message = code === 'session/not-found'
|
|
779
|
+
? 'the DSH session recorded for the named task no longer exists, so it was not continued'
|
|
780
|
+
: 'the DSH session recorded for the named task could not be resumed';
|
|
781
|
+
return new SessionPlacementError(failureCode ?? SESSION_CODES.resumeFailed, message, {
|
|
782
|
+
cause: code,
|
|
783
|
+
detail: diagnostic(error?.message ?? error, 200),
|
|
784
|
+
workspaceId: workspace.workspaceId,
|
|
785
|
+
continueFromTaskId: parentTaskId,
|
|
786
|
+
});
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
/**
|
|
790
|
+
* Durable, minimal task-thread identity map: task id -> DSH ids and paths.
|
|
791
|
+
*
|
|
792
|
+
* The map is keyed by TASK, not by directory, because a directory may hold many
|
|
793
|
+
* independent conversations and only an explicit `continueFromTaskId` may join
|
|
794
|
+
* them. One row holds {@link RECORD_FIELDS} and nothing else: a follow-up needs
|
|
795
|
+
* exactly the identity of the thread it continues, the two paths a continuation is
|
|
796
|
+
* validated against, and the safe ownership facts about a managed tree.
|
|
797
|
+
*
|
|
798
|
+
* Writes are serialized and land through a temporary sibling plus rename, so a
|
|
799
|
+
* concurrent save cannot lose an earlier one and a crash leaves either the old or
|
|
800
|
+
* the new complete document. Reads are cached after the first successful load.
|
|
801
|
+
*/
|
|
802
|
+
export class SessionStore {
|
|
803
|
+
/**
|
|
804
|
+
* @param {string} dataDir - plugin data directory.
|
|
805
|
+
* @param {object} [options] - `fs` seam (`readFile`, `writeFile`, `rename`,
|
|
806
|
+
* `mkdir`, `rm`) and `logger`.
|
|
807
|
+
*/
|
|
808
|
+
constructor(dataDir, options = {}) {
|
|
809
|
+
if (typeof dataDir !== 'string' || dataDir.trim() === '') {
|
|
810
|
+
throw new TypeError('SessionStore needs a data directory');
|
|
811
|
+
}
|
|
812
|
+
this.dir = dataDir;
|
|
813
|
+
this.path = join(dataDir, SESSIONS_FILE);
|
|
814
|
+
this.fs = options.fs ?? { readFile, writeFile, rename, mkdir, rm };
|
|
815
|
+
this.logger = options.logger ?? null;
|
|
816
|
+
this.records = null;
|
|
817
|
+
this.loading = null;
|
|
818
|
+
this.queue = Promise.resolve();
|
|
819
|
+
this.disposed = false;
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
/**
|
|
823
|
+
* Read the map, newest first.
|
|
824
|
+
* @returns {Promise<object[]>} detached records.
|
|
825
|
+
*/
|
|
826
|
+
async list() {
|
|
827
|
+
return (await this.ensureLoaded()).map((record) => ({ ...record }));
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
/**
|
|
831
|
+
* Look up the thread recorded for one task.
|
|
832
|
+
*
|
|
833
|
+
* A legacy row (from a build that keyed the map by directory) is reachable by its
|
|
834
|
+
* task id only when it carries one; a directory-keyed row never answers a task
|
|
835
|
+
* lookup, which is what keeps the migrated rows incapable of an implicit reuse.
|
|
836
|
+
* @param {string} taskId - task id.
|
|
837
|
+
* @returns {Promise<object | null>} detached record, or null.
|
|
838
|
+
*/
|
|
839
|
+
async get(taskId) {
|
|
840
|
+
const key = typeof taskId === 'string' ? taskId.trim() : '';
|
|
841
|
+
if (key === '') return null;
|
|
842
|
+
const found = (await this.ensureLoaded()).find((record) => record.taskId === key);
|
|
843
|
+
return found === undefined ? null : { ...found };
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
/**
|
|
847
|
+
* Record the thread one task drove, replacing any earlier row for that task.
|
|
848
|
+
* @param {object} entry - `taskId`, `sourcePath`, `executionPath`, `workspaceId`,
|
|
849
|
+
* `sessionId`, optional `isolation`, `worktreeId`, `worktreeState`.
|
|
850
|
+
* @returns {Promise<object>} the stored record.
|
|
851
|
+
* @throws {TypeError} for an entry that is not a usable identity.
|
|
852
|
+
*/
|
|
853
|
+
async put(entry) {
|
|
854
|
+
if (this.disposed) throw new Error('the session map has been disposed');
|
|
855
|
+
const record = projectSessionRecord(entry);
|
|
856
|
+
const run = this.enqueue(async () => {
|
|
857
|
+
const base = await this.ensureLoaded();
|
|
858
|
+
const next = base.filter((item) => item.taskId !== record.taskId);
|
|
859
|
+
next.push(record);
|
|
860
|
+
await this.writeDocument(next);
|
|
861
|
+
this.records = next;
|
|
862
|
+
return { ...record };
|
|
863
|
+
});
|
|
864
|
+
return await run;
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
/**
|
|
868
|
+
* Forget the thread recorded for one task.
|
|
869
|
+
* @param {string} taskId - task id.
|
|
870
|
+
* @returns {Promise<boolean>} whether a record was removed.
|
|
871
|
+
*/
|
|
872
|
+
async forget(taskId) {
|
|
873
|
+
if (this.disposed) throw new Error('the session map has been disposed');
|
|
874
|
+
const key = typeof taskId === 'string' ? taskId.trim() : '';
|
|
875
|
+
if (key === '') return false;
|
|
876
|
+
const run = this.enqueue(async () => {
|
|
877
|
+
const base = await this.ensureLoaded();
|
|
878
|
+
const next = base.filter((item) => item.taskId !== key);
|
|
879
|
+
if (next.length === base.length) return false;
|
|
880
|
+
await this.writeDocument(next);
|
|
881
|
+
this.records = next;
|
|
882
|
+
return true;
|
|
883
|
+
});
|
|
884
|
+
return await run;
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
/**
|
|
888
|
+
* Wait for queued writes and stop accepting new ones.
|
|
889
|
+
* @returns {Promise<void>} resolves when settled.
|
|
890
|
+
*/
|
|
891
|
+
async dispose() {
|
|
892
|
+
if (this.disposed) return;
|
|
893
|
+
await this.queue;
|
|
894
|
+
this.disposed = true;
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
/**
|
|
898
|
+
* Run one mutation after every earlier one.
|
|
899
|
+
* @param {() => Promise<object>} work - queued mutation.
|
|
900
|
+
* @returns {Promise<object>} its result.
|
|
901
|
+
*/
|
|
902
|
+
enqueue(work) {
|
|
903
|
+
const run = this.queue.then(work);
|
|
904
|
+
this.queue = run.then(() => undefined, () => undefined);
|
|
905
|
+
return run;
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
/**
|
|
909
|
+
* Load once, sharing the physical read between concurrent callers.
|
|
910
|
+
* @returns {Promise<object[]>} records, in document order.
|
|
911
|
+
*/
|
|
912
|
+
async ensureLoaded() {
|
|
913
|
+
if (this.records !== null) return this.records;
|
|
914
|
+
if (this.loading === null) {
|
|
915
|
+
this.loading = this.readOnce().finally(() => { this.loading = null; });
|
|
916
|
+
}
|
|
917
|
+
return await this.loading;
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
/**
|
|
921
|
+
* Read and normalize the document. A missing file is an empty map; an
|
|
922
|
+
* unreadable or malformed one is reported and treated as empty, because this map
|
|
923
|
+
* is an index for continuing a thread and never an authority over a run.
|
|
924
|
+
* @returns {Promise<object[]>} usable records.
|
|
925
|
+
*/
|
|
926
|
+
async readOnce() {
|
|
927
|
+
let raw;
|
|
928
|
+
try {
|
|
929
|
+
raw = await this.fs.readFile(this.path, 'utf8');
|
|
930
|
+
} catch (error) {
|
|
931
|
+
if (error?.code === 'ENOENT') {
|
|
932
|
+
this.records = [];
|
|
933
|
+
return this.records;
|
|
934
|
+
}
|
|
935
|
+
this.logger?.warn?.('dsh-delegate: the session map could not be read', diagnostic(error?.message ?? error, 200));
|
|
936
|
+
this.records = [];
|
|
937
|
+
return this.records;
|
|
938
|
+
}
|
|
939
|
+
let parsed;
|
|
940
|
+
try {
|
|
941
|
+
parsed = JSON.parse(raw);
|
|
942
|
+
} catch {
|
|
943
|
+
this.logger?.warn?.('dsh-delegate: the session map is not valid JSON; starting from an empty map (the file was left as found)');
|
|
944
|
+
this.records = [];
|
|
945
|
+
return this.records;
|
|
946
|
+
}
|
|
947
|
+
const stored = Array.isArray(parsed?.sessions) ? parsed.sessions : [];
|
|
948
|
+
const records = [];
|
|
949
|
+
for (const entry of stored) {
|
|
950
|
+
const migrated = migrateSessionRow(entry);
|
|
951
|
+
if (migrated === null) {
|
|
952
|
+
// A row that is not a usable task identity (including every directory-keyed
|
|
953
|
+
// row from a build that recorded no task id) is dropped, never guessed at:
|
|
954
|
+
// the identity it would carry is what a continuation would act on.
|
|
955
|
+
if (entry !== null && typeof entry === 'object') {
|
|
956
|
+
this.logger?.warn?.('dsh-delegate: one session map row carried no task identity and was ignored');
|
|
957
|
+
}
|
|
958
|
+
continue;
|
|
959
|
+
}
|
|
960
|
+
try {
|
|
961
|
+
records.push(projectSessionRecord(migrated));
|
|
962
|
+
} catch {
|
|
963
|
+
this.logger?.warn?.('dsh-delegate: one session map row was unusable and was ignored');
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
this.records = records;
|
|
967
|
+
return this.records;
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
/**
|
|
971
|
+
* Replace the document atomically (temporary sibling, then rename).
|
|
972
|
+
* @param {object[]} records - records to store.
|
|
973
|
+
* @returns {Promise<void>} resolves after the rename.
|
|
974
|
+
*/
|
|
975
|
+
async writeDocument(records) {
|
|
976
|
+
const content = `${JSON.stringify({
|
|
977
|
+
schemaVersion: 2,
|
|
978
|
+
updatedAt: new Date().toISOString(),
|
|
979
|
+
sessions: records,
|
|
980
|
+
}, null, 2)}\n`;
|
|
981
|
+
const temp = `${this.path}.${process.pid}.${Date.now()}.tmp`;
|
|
982
|
+
try {
|
|
983
|
+
await this.fs.mkdir(dirname(this.path), { recursive: true, mode: 0o700 });
|
|
984
|
+
await this.fs.writeFile(temp, content, { mode: 0o600 });
|
|
985
|
+
await this.fs.rename(temp, this.path);
|
|
986
|
+
} catch (error) {
|
|
987
|
+
await this.fs.rm?.(temp, { force: true }).catch(() => undefined);
|
|
988
|
+
throw error;
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
/**
|
|
994
|
+
* Lift one stored row onto the current shape, or refuse it.
|
|
995
|
+
*
|
|
996
|
+
* Two stored generations exist:
|
|
997
|
+
*
|
|
998
|
+
* * **schema 2** — keyed by task id; this is what this build writes and reads;
|
|
999
|
+
* * **schema 1** — keyed by canonical execution directory, `{ path, workspaceId,
|
|
1000
|
+
* sessionId, updatedAt }`, written by a build that offered a directory-level
|
|
1001
|
+
* `reuse` mode. It recorded no task id, so it cannot name a task thread and is
|
|
1002
|
+
* therefore *not* usable as a continuation parent. It is ignored on read and
|
|
1003
|
+
* never acts as an implicit source of reuse: the map is keyed by task, and a
|
|
1004
|
+
* legacy row has no task.
|
|
1005
|
+
*
|
|
1006
|
+
* A row that already carries a task id is accepted from either generation, so a
|
|
1007
|
+
* hand-edited or forward-compatible document is read on its own facts.
|
|
1008
|
+
* @param {unknown} entry - one stored row.
|
|
1009
|
+
* @returns {object | null} a row this build can use, or null.
|
|
1010
|
+
*/
|
|
1011
|
+
export function migrateSessionRow(entry) {
|
|
1012
|
+
if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) return null;
|
|
1013
|
+
const taskId = typeof entry.taskId === 'string' ? entry.taskId.trim() : '';
|
|
1014
|
+
if (taskId === '') return null;
|
|
1015
|
+
return entry;
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
/**
|
|
1019
|
+
* Project one stored row onto the exact field set this module owns.
|
|
1020
|
+
*
|
|
1021
|
+
* Everything omitted here is omitted on purpose: no prompt, no transcript, no model
|
|
1022
|
+
* output, no usage figure and no credential has a field, so a continuation can
|
|
1023
|
+
* carry conversation identity and never conversation content.
|
|
1024
|
+
* @param {unknown} value - candidate row.
|
|
1025
|
+
* @returns {object} bounded record.
|
|
1026
|
+
* @throws {TypeError} when the row is not a usable identity.
|
|
1027
|
+
*/
|
|
1028
|
+
function projectSessionRecord(value) {
|
|
1029
|
+
if (value === null || typeof value !== 'object') throw new TypeError('a session map row must be an object');
|
|
1030
|
+
const taskId = typeof value.taskId === 'string' ? value.taskId.trim() : '';
|
|
1031
|
+
const sessionId = typeof value.sessionId === 'string' ? value.sessionId.trim() : '';
|
|
1032
|
+
if (taskId === '') throw new TypeError('a session map row needs a taskId');
|
|
1033
|
+
if (sessionId === '') throw new TypeError('a session map row needs a sessionId');
|
|
1034
|
+
const executionPath = firstPath(value.executionPath, value.path);
|
|
1035
|
+
const sourcePath = firstPath(value.sourcePath, value.executionPath, value.path);
|
|
1036
|
+
const isolation = typeof value.isolation === 'string' && ISOLATION_MODES.includes(value.isolation)
|
|
1037
|
+
? value.isolation
|
|
1038
|
+
: null;
|
|
1039
|
+
return {
|
|
1040
|
+
taskId,
|
|
1041
|
+
sourcePath,
|
|
1042
|
+
executionPath,
|
|
1043
|
+
workspaceId: typeof value.workspaceId === 'string' ? value.workspaceId.trim() : '',
|
|
1044
|
+
sessionId,
|
|
1045
|
+
isolation,
|
|
1046
|
+
worktreeId: typeof value.worktreeId === 'string' && value.worktreeId.trim() !== '' ? value.worktreeId.trim() : null,
|
|
1047
|
+
worktreeState: typeof value.worktreeState === 'string' && value.worktreeState.trim() !== ''
|
|
1048
|
+
? value.worktreeState.trim()
|
|
1049
|
+
: null,
|
|
1050
|
+
updatedAt: Number.isFinite(value.updatedAt) ? Math.trunc(value.updatedAt) : Date.now(),
|
|
1051
|
+
};
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
/**
|
|
1055
|
+
* The first usable absolute-looking path among the candidates, or null.
|
|
1056
|
+
* @param {...unknown} candidates - path candidates.
|
|
1057
|
+
* @returns {string | null} chosen path.
|
|
1058
|
+
*/
|
|
1059
|
+
function firstPath(...candidates) {
|
|
1060
|
+
for (const candidate of candidates) {
|
|
1061
|
+
if (typeof candidate === 'string' && candidate.trim() !== '') return candidate.trim();
|
|
1062
|
+
}
|
|
1063
|
+
return null;
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
/**
|
|
1067
|
+
* Record the thread a run actually drove.
|
|
1068
|
+
*
|
|
1069
|
+
* Only identity and provenance are written; nothing the model produced and nothing
|
|
1070
|
+
* the harness used to authenticate reaches this call.
|
|
1071
|
+
* @param {object | null | undefined} store - a {@link SessionStore} or null.
|
|
1072
|
+
* @param {object} placement - value returned by {@link placeSession}.
|
|
1073
|
+
* @param {object} entry - `taskId`, `sourcePath`, `executionPath`, optional
|
|
1074
|
+
* `isolation`, `worktreeId`, `worktreeState`.
|
|
1075
|
+
* @returns {Promise<boolean>} whether a record was written.
|
|
1076
|
+
*/
|
|
1077
|
+
export async function rememberSession(store, placement, entry) {
|
|
1078
|
+
if (store === null || store === undefined || typeof store.put !== 'function') return false;
|
|
1079
|
+
if (placement === null || typeof placement !== 'object') return false;
|
|
1080
|
+
const sessionId = typeof placement.sessionId === 'string' ? placement.sessionId : '';
|
|
1081
|
+
if (sessionId === '') return false;
|
|
1082
|
+
const target = entry ?? {};
|
|
1083
|
+
const taskId = typeof target.taskId === 'string' ? target.taskId.trim() : '';
|
|
1084
|
+
const executionPath = typeof target.executionPath === 'string' ? target.executionPath.trim() : '';
|
|
1085
|
+
// A row without a task and an execution path names nothing a continuation could
|
|
1086
|
+
// validate, so it is not written at all rather than half-written.
|
|
1087
|
+
if (taskId === '' || executionPath === '') return false;
|
|
1088
|
+
await store.put({
|
|
1089
|
+
taskId,
|
|
1090
|
+
executionPath,
|
|
1091
|
+
sourcePath: typeof target.sourcePath === 'string' && target.sourcePath.trim() !== ''
|
|
1092
|
+
? target.sourcePath.trim()
|
|
1093
|
+
: executionPath,
|
|
1094
|
+
workspaceId: typeof placement.workspaceId === 'string' ? placement.workspaceId : '',
|
|
1095
|
+
sessionId,
|
|
1096
|
+
isolation: typeof target.isolation === 'string' ? target.isolation : null,
|
|
1097
|
+
worktreeId: typeof target.worktreeId === 'string' ? target.worktreeId : null,
|
|
1098
|
+
worktreeState: typeof target.worktreeState === 'string' ? target.worktreeState : null,
|
|
1099
|
+
});
|
|
1100
|
+
return true;
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
export { RECORD_FIELDS };
|