@1agents/acp-service 0.10.10 → 0.10.12
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/README.md +26 -0
- package/dist/bin/acp-service.js +6 -0
- package/dist/bin/dsh.d.ts +21 -0
- package/dist/bin/dsh.js +171 -0
- package/dist/src/a2a/gateway.d.ts +12 -0
- package/dist/src/a2a/gateway.js +192 -10
- package/dist/src/catalog-descriptors.js +10 -0
- package/dist/src/dsh-archive.d.ts +123 -0
- package/dist/src/dsh-archive.js +99 -0
- package/dist/src/dsh-host-client.d.ts +97 -0
- package/dist/src/dsh-host-client.js +275 -0
- package/dist/src/dsh-registry-file.d.ts +22 -0
- package/dist/src/dsh-registry-file.js +55 -0
- package/dist/src/dsh-session-files.d.ts +7 -0
- package/dist/src/dsh-session-files.js +63 -0
- package/package.json +1 -1
- package/skills/acp-service/SKILL.md +1 -1
- package/vendor/dsh/README.md +2 -0
- package/vendor/runtime/dist/{agent-registry-R7A3MSpr.js → agent-registry-DxcyXXqb.js} +5 -1
- package/vendor/runtime/dist/agent-registry-DxcyXXqb.js.map +1 -0
- package/vendor/runtime/dist/agent-registry.d.ts.map +1 -1
- package/vendor/runtime/dist/agent-registry.js +1 -1
- package/vendor/runtime/dist/{cli-BwanDcOo.js → cli-BKmMxgix.js} +4 -4
- package/vendor/runtime/dist/{cli-BwanDcOo.js.map → cli-BKmMxgix.js.map} +1 -1
- package/vendor/runtime/dist/cli.js +9 -9
- package/vendor/runtime/dist/docs-site/agents.html +1 -1
- package/vendor/runtime/dist/{flows-CzLUHUTS.js → flows-VrII9VKZ.js} +5 -5
- package/vendor/runtime/dist/{flows-CzLUHUTS.js.map → flows-VrII9VKZ.js.map} +1 -1
- package/vendor/runtime/dist/flows.js +1 -1
- package/vendor/runtime/dist/{invocation-options-B6pIpdpR.js → invocation-options-DHMZ5Rrb.js} +5 -5
- package/vendor/runtime/dist/{invocation-options-B6pIpdpR.js.map → invocation-options-DHMZ5Rrb.js.map} +1 -1
- package/vendor/runtime/dist/{ipc-ivLtSAdL.js → ipc-CNNM5DP_.js} +2 -2
- package/vendor/runtime/dist/{ipc-ivLtSAdL.js.map → ipc-CNNM5DP_.js.map} +1 -1
- package/vendor/runtime/dist/{output-BqKnXXb0.js → output-DtzXtiBc.js} +3 -3
- package/vendor/runtime/dist/{output-BqKnXXb0.js.map → output-DtzXtiBc.js.map} +1 -1
- package/vendor/runtime/dist/{queue-owner-runtime-DXJND10J.js → queue-owner-runtime-ehuh3SQU.js} +3 -3
- package/vendor/runtime/dist/{queue-owner-runtime-DXJND10J.js.map → queue-owner-runtime-ehuh3SQU.js.map} +1 -1
- package/vendor/runtime/dist/runtime.js +4 -4
- package/vendor/runtime/dist/{session-watch-BHB3_PXm.js → session-watch-CbKfGRkZ.js} +4 -4
- package/vendor/runtime/dist/{session-watch-BHB3_PXm.js.map → session-watch-CbKfGRkZ.js.map} +1 -1
- package/vendor/runtime/dist/{watch-UjokHUfS.js → watch-BGt4kcE6.js} +2 -2
- package/vendor/runtime/dist/{watch-UjokHUfS.js.map → watch-BGt4kcE6.js.map} +1 -1
- package/vendor/runtime/skills/acpx/SKILL.md +1 -0
- package/vendor/runtime/dist/agent-registry-R7A3MSpr.js.map +0 -1
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Manual archiving of silent DSH sessions.
|
|
3
|
+
*
|
|
4
|
+
* DSH owns the durable archive set: archiving a session hides it from the
|
|
5
|
+
* workspace grouping and stops every model step for it and its subagent
|
|
6
|
+
* descendants. This module only decides *which* sessions to hand to that
|
|
7
|
+
* API. It never deletes sessions or their logs, and a pinned session stays a
|
|
8
|
+
* manual decision unless the caller explicitly opts in.
|
|
9
|
+
*
|
|
10
|
+
* The work runs against a live DSH Host over its Typert RPC, because the
|
|
11
|
+
* workspace registry keeps its state in memory: writing the storage file
|
|
12
|
+
* behind a running Host would be overwritten by its next write.
|
|
13
|
+
*/
|
|
14
|
+
/** One day in milliseconds. */
|
|
15
|
+
export declare const DAY_MS: number;
|
|
16
|
+
/** A session as the Host reports it. */
|
|
17
|
+
export interface DshSessionSummary {
|
|
18
|
+
readonly sessionId: string;
|
|
19
|
+
/** Epoch milliseconds of the session's last recorded activity. */
|
|
20
|
+
readonly updatedAt: number;
|
|
21
|
+
readonly cwd?: string;
|
|
22
|
+
readonly running?: boolean;
|
|
23
|
+
readonly blank?: boolean;
|
|
24
|
+
readonly agentAvailable?: boolean;
|
|
25
|
+
readonly parentSessionId?: string;
|
|
26
|
+
readonly origin?: string;
|
|
27
|
+
readonly projections?: {
|
|
28
|
+
readonly values?: {
|
|
29
|
+
readonly title?: string;
|
|
30
|
+
};
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
/** The registry sets the CLI reads and writes. */
|
|
34
|
+
export interface ArchiveRegistryState {
|
|
35
|
+
readonly archivedSessionIds: readonly string[];
|
|
36
|
+
readonly pinnedSessionIds: readonly string[];
|
|
37
|
+
}
|
|
38
|
+
/** The live Host calls the archive pass needs. */
|
|
39
|
+
export interface DshArchiveClient {
|
|
40
|
+
/** Every session the Host can see, live or persisted. */
|
|
41
|
+
listSessions(): Promise<readonly DshSessionSummary[]>;
|
|
42
|
+
/** The registry's current archive and pin sets. */
|
|
43
|
+
readRegistry(): Promise<ArchiveRegistryState>;
|
|
44
|
+
/** Ask the Host to archive one session. */
|
|
45
|
+
archiveSession(sessionId: string, options: {
|
|
46
|
+
readonly stopActivity: boolean;
|
|
47
|
+
}): Promise<void>;
|
|
48
|
+
}
|
|
49
|
+
/** How the pass selects its targets. */
|
|
50
|
+
export interface ArchivePlanOptions {
|
|
51
|
+
/** Sessions idle for at least this many milliseconds are candidates. */
|
|
52
|
+
readonly inactivityMs: number;
|
|
53
|
+
/** Current time in epoch milliseconds. */
|
|
54
|
+
readonly now: number;
|
|
55
|
+
/** Archive pinned sessions too. Off by default: a pin is the explicit "keep this visible" signal. */
|
|
56
|
+
readonly includePinned?: boolean;
|
|
57
|
+
/** Stop a session's running work to archive it. Off by default: running sessions are skipped. */
|
|
58
|
+
readonly stopActivity?: boolean;
|
|
59
|
+
/** Durable session file modification times, by session id. */
|
|
60
|
+
readonly fileMtimes?: ReadonlyMap<string, number>;
|
|
61
|
+
}
|
|
62
|
+
/** One session the pass would archive, with the reason it was selected. */
|
|
63
|
+
export interface ArchiveCandidate {
|
|
64
|
+
readonly sessionId: string;
|
|
65
|
+
readonly title: string;
|
|
66
|
+
readonly cwd: string;
|
|
67
|
+
/** Epoch milliseconds of the session's last activity. */
|
|
68
|
+
readonly lastActiveAt: number;
|
|
69
|
+
/** Whole days since that activity, rounded down. */
|
|
70
|
+
readonly idleDays: number;
|
|
71
|
+
/** Whether the session's last activity came from its durable file. */
|
|
72
|
+
readonly fromFile: boolean;
|
|
73
|
+
}
|
|
74
|
+
/** A session the pass deliberately left alone. */
|
|
75
|
+
export interface ArchiveSkip {
|
|
76
|
+
readonly sessionId: string;
|
|
77
|
+
readonly reason: 'pinned' | 'running' | 'already-archived';
|
|
78
|
+
readonly title: string;
|
|
79
|
+
}
|
|
80
|
+
/** The computed plan, before anything is written. */
|
|
81
|
+
export interface ArchivePlan {
|
|
82
|
+
readonly candidates: readonly ArchiveCandidate[];
|
|
83
|
+
readonly skipped: readonly ArchiveSkip[];
|
|
84
|
+
readonly totalSessions: number;
|
|
85
|
+
readonly alreadyArchived: number;
|
|
86
|
+
}
|
|
87
|
+
/** The result of executing a plan. */
|
|
88
|
+
export interface ArchiveRunResult {
|
|
89
|
+
readonly archived: readonly string[];
|
|
90
|
+
readonly failed: readonly {
|
|
91
|
+
readonly sessionId: string;
|
|
92
|
+
readonly error: string;
|
|
93
|
+
}[];
|
|
94
|
+
readonly skipped: readonly ArchiveSkip[];
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Compute the sessions to archive, without writing anything.
|
|
98
|
+
*
|
|
99
|
+
* Last activity is the later of the Host's own recency (`updatedAt`, the
|
|
100
|
+
* creation time or the last real user message) and the modification time of
|
|
101
|
+
* the session's durable log. That covers both readings of "last activity" —
|
|
102
|
+
* the last message block and the backing file's mtime — and keeps a cold
|
|
103
|
+
* session whose file was touched recently out of the candidate set.
|
|
104
|
+
*
|
|
105
|
+
* @param client - the live Host calls.
|
|
106
|
+
* @param options - threshold, clock and selection policy.
|
|
107
|
+
* @returns the plan and the sessions left alone.
|
|
108
|
+
*/
|
|
109
|
+
export declare function planArchive(client: DshArchiveClient, options: ArchivePlanOptions): Promise<ArchivePlan>;
|
|
110
|
+
/**
|
|
111
|
+
* Archive the planned sessions through the Host, one at a time.
|
|
112
|
+
*
|
|
113
|
+
* Each session is archived on its own so one refusal does not stop the rest.
|
|
114
|
+
* A refusal is reported with its message; the caller decides what to do.
|
|
115
|
+
*
|
|
116
|
+
* @param client - the live Host calls.
|
|
117
|
+
* @param plan - candidates from {@link planArchive}.
|
|
118
|
+
* @param options - whether running work may be stopped.
|
|
119
|
+
* @returns the archived ids and the failures.
|
|
120
|
+
*/
|
|
121
|
+
export declare function runArchive(client: DshArchiveClient, plan: ArchivePlan, options?: {
|
|
122
|
+
readonly stopActivity?: boolean;
|
|
123
|
+
}): Promise<ArchiveRunResult>;
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Manual archiving of silent DSH sessions.
|
|
3
|
+
*
|
|
4
|
+
* DSH owns the durable archive set: archiving a session hides it from the
|
|
5
|
+
* workspace grouping and stops every model step for it and its subagent
|
|
6
|
+
* descendants. This module only decides *which* sessions to hand to that
|
|
7
|
+
* API. It never deletes sessions or their logs, and a pinned session stays a
|
|
8
|
+
* manual decision unless the caller explicitly opts in.
|
|
9
|
+
*
|
|
10
|
+
* The work runs against a live DSH Host over its Typert RPC, because the
|
|
11
|
+
* workspace registry keeps its state in memory: writing the storage file
|
|
12
|
+
* behind a running Host would be overwritten by its next write.
|
|
13
|
+
*/
|
|
14
|
+
/** One day in milliseconds. */
|
|
15
|
+
export const DAY_MS = 24 * 60 * 60 * 1000;
|
|
16
|
+
/**
|
|
17
|
+
* Compute the sessions to archive, without writing anything.
|
|
18
|
+
*
|
|
19
|
+
* Last activity is the later of the Host's own recency (`updatedAt`, the
|
|
20
|
+
* creation time or the last real user message) and the modification time of
|
|
21
|
+
* the session's durable log. That covers both readings of "last activity" —
|
|
22
|
+
* the last message block and the backing file's mtime — and keeps a cold
|
|
23
|
+
* session whose file was touched recently out of the candidate set.
|
|
24
|
+
*
|
|
25
|
+
* @param client - the live Host calls.
|
|
26
|
+
* @param options - threshold, clock and selection policy.
|
|
27
|
+
* @returns the plan and the sessions left alone.
|
|
28
|
+
*/
|
|
29
|
+
export async function planArchive(client, options) {
|
|
30
|
+
if (!Number.isSafeInteger(options.now) || options.now < 0)
|
|
31
|
+
throw new Error('now must be a non-negative safe integer');
|
|
32
|
+
if (!Number.isSafeInteger(options.inactivityMs) || options.inactivityMs < 1)
|
|
33
|
+
throw new Error('inactivityMs must be a positive integer');
|
|
34
|
+
const [sessions, registry] = await Promise.all([client.listSessions(), client.readRegistry()]);
|
|
35
|
+
const archived = new Set(registry.archivedSessionIds);
|
|
36
|
+
const pinned = new Set(registry.pinnedSessionIds);
|
|
37
|
+
const mtimes = options.fileMtimes ?? new Map();
|
|
38
|
+
const cutoff = options.now - options.inactivityMs;
|
|
39
|
+
const candidates = [];
|
|
40
|
+
const skipped = [];
|
|
41
|
+
for (const session of sessions) {
|
|
42
|
+
if (archived.has(session.sessionId))
|
|
43
|
+
continue;
|
|
44
|
+
const title = session.projections?.values?.title ?? '';
|
|
45
|
+
if (session.running === true) {
|
|
46
|
+
skipped.push({ sessionId: session.sessionId, reason: 'running', title });
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
if (pinned.has(session.sessionId) && options.includePinned !== true) {
|
|
50
|
+
skipped.push({ sessionId: session.sessionId, reason: 'pinned', title });
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
const fileMtime = mtimes.get(session.sessionId) ?? 0;
|
|
54
|
+
const fromFile = fileMtime > (session.updatedAt ?? 0);
|
|
55
|
+
const lastActiveAt = Math.max(session.updatedAt ?? 0, fileMtime);
|
|
56
|
+
if (lastActiveAt >= cutoff)
|
|
57
|
+
continue;
|
|
58
|
+
candidates.push({
|
|
59
|
+
sessionId: session.sessionId,
|
|
60
|
+
title,
|
|
61
|
+
cwd: session.cwd ?? '',
|
|
62
|
+
lastActiveAt,
|
|
63
|
+
idleDays: Math.floor((options.now - lastActiveAt) / DAY_MS),
|
|
64
|
+
fromFile,
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
candidates.sort((left, right) => left.lastActiveAt - right.lastActiveAt);
|
|
68
|
+
return {
|
|
69
|
+
candidates,
|
|
70
|
+
skipped,
|
|
71
|
+
totalSessions: sessions.length,
|
|
72
|
+
alreadyArchived: sessions.filter(session => archived.has(session.sessionId)).length,
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Archive the planned sessions through the Host, one at a time.
|
|
77
|
+
*
|
|
78
|
+
* Each session is archived on its own so one refusal does not stop the rest.
|
|
79
|
+
* A refusal is reported with its message; the caller decides what to do.
|
|
80
|
+
*
|
|
81
|
+
* @param client - the live Host calls.
|
|
82
|
+
* @param plan - candidates from {@link planArchive}.
|
|
83
|
+
* @param options - whether running work may be stopped.
|
|
84
|
+
* @returns the archived ids and the failures.
|
|
85
|
+
*/
|
|
86
|
+
export async function runArchive(client, plan, options = {}) {
|
|
87
|
+
const archived = [];
|
|
88
|
+
const failed = [];
|
|
89
|
+
for (const candidate of plan.candidates) {
|
|
90
|
+
try {
|
|
91
|
+
await client.archiveSession(candidate.sessionId, { stopActivity: options.stopActivity === true });
|
|
92
|
+
archived.push(candidate.sessionId);
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
failed.push({ sessionId: candidate.sessionId, error: error instanceof Error ? error.message : String(error) });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return { archived, failed, skipped: plan.skipped };
|
|
99
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import type { ArchiveRegistryState, DshArchiveClient, DshSessionSummary } from './dsh-archive.js';
|
|
2
|
+
/** A Host endpoint the CLI can reach. */
|
|
3
|
+
export interface DshEndpoint {
|
|
4
|
+
readonly origin: string;
|
|
5
|
+
readonly authority: string;
|
|
6
|
+
}
|
|
7
|
+
/** An RPC failure reported by the Host. */
|
|
8
|
+
export declare class DshRpcError extends Error {
|
|
9
|
+
readonly code: string;
|
|
10
|
+
constructor(code: string, message: string);
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Read the browser-session signing secret from the local credential store.
|
|
14
|
+
*
|
|
15
|
+
* The store is a YAML document; this reads the one field it needs rather than
|
|
16
|
+
* taking a YAML dependency, and never returns the secret to the caller.
|
|
17
|
+
*
|
|
18
|
+
* @param credentialsPath - path to the credential document.
|
|
19
|
+
* @returns the signing secret.
|
|
20
|
+
*/
|
|
21
|
+
export declare function readBrowserSessionSecret(credentialsPath: string): Buffer;
|
|
22
|
+
/**
|
|
23
|
+
* Mint the signed browser-session cookie for one authority.
|
|
24
|
+
*
|
|
25
|
+
* @param secret - the signing secret from the credential store.
|
|
26
|
+
* @param authority - the host:port the cookie is scoped to.
|
|
27
|
+
* @returns the cookie header value.
|
|
28
|
+
*/
|
|
29
|
+
export declare function mintSessionCookie(secret: Buffer, authority: string): string;
|
|
30
|
+
/**
|
|
31
|
+
* List the loopback TCP ports this machine is listening on.
|
|
32
|
+
*
|
|
33
|
+
* The desktop app binds an ephemeral port, so the CLI discovers the Host by
|
|
34
|
+
* probing local listeners rather than by a configured address.
|
|
35
|
+
*
|
|
36
|
+
* @returns the loopback ports, ascending.
|
|
37
|
+
*/
|
|
38
|
+
export declare function listLoopbackPorts(): number[];
|
|
39
|
+
/**
|
|
40
|
+
* Ask one origin whether it is a DSH Host that answers the session API.
|
|
41
|
+
*
|
|
42
|
+
* @param origin - the origin to probe.
|
|
43
|
+
* @param cookie - the minted cookie for that origin's authority.
|
|
44
|
+
* @returns whether the origin answered a session list.
|
|
45
|
+
*/
|
|
46
|
+
export declare function probeHost(origin: string, cookie: string): Promise<boolean>;
|
|
47
|
+
/**
|
|
48
|
+
* Find a reachable DSH Host.
|
|
49
|
+
*
|
|
50
|
+
* An explicit origin is authoritative: the CLI uses the first named origin
|
|
51
|
+
* that answers, so a caller can target one instance on purpose. Without one
|
|
52
|
+
* the CLI probes the machine's loopback listeners, because the desktop app
|
|
53
|
+
* binds an ephemeral port that nothing else records; there it prefers a Host
|
|
54
|
+
* whose registry already holds every archived id, since two Hosts can share
|
|
55
|
+
* one DSH home and the older one's copy would drop the newer archives on its
|
|
56
|
+
* next write.
|
|
57
|
+
*
|
|
58
|
+
* @param origins - explicit origins from the command line.
|
|
59
|
+
* @param secret - the browser-session signing secret.
|
|
60
|
+
* @param documentArchived - archive ids the durable document records, when known.
|
|
61
|
+
* @returns the chosen origin.
|
|
62
|
+
*/
|
|
63
|
+
export declare function discoverHost(origins: readonly string[], secret: Buffer, documentArchived?: readonly string[]): Promise<DshEndpoint>;
|
|
64
|
+
/** A live DSH Host reached over RPC. */
|
|
65
|
+
export declare class DshHostClient implements DshArchiveClient {
|
|
66
|
+
private readonly endpoint;
|
|
67
|
+
private readonly cookie;
|
|
68
|
+
private rpcId;
|
|
69
|
+
/** The archive set this Host most recently reported, for the freshness check. */
|
|
70
|
+
private lastArchivedSessionIds;
|
|
71
|
+
constructor(endpoint: DshEndpoint, cookie: string);
|
|
72
|
+
/**
|
|
73
|
+
* Call one Host method.
|
|
74
|
+
*
|
|
75
|
+
* @param method - the `namespace/method` endpoint.
|
|
76
|
+
* @param args - the method's arguments.
|
|
77
|
+
* @returns the decoded result value.
|
|
78
|
+
*/
|
|
79
|
+
call<T>(method: string, args: Record<string, unknown>): Promise<T>;
|
|
80
|
+
listSessions(): Promise<readonly DshSessionSummary[]>;
|
|
81
|
+
readRegistry(): Promise<ArchiveRegistryState>;
|
|
82
|
+
archiveSession(sessionId: string, options: {
|
|
83
|
+
readonly stopActivity: boolean;
|
|
84
|
+
}): Promise<void>;
|
|
85
|
+
/**
|
|
86
|
+
* Refuse to write through a Host whose registry is behind the document.
|
|
87
|
+
*
|
|
88
|
+
* The Host holds the registry in memory and rewrites the whole document on
|
|
89
|
+
* every change, so a Host that started before another Host wrote the
|
|
90
|
+
* document would drop the newer archive entries. The command reports this
|
|
91
|
+
* instead of silently undoing someone else's archives.
|
|
92
|
+
*
|
|
93
|
+
* @param documentArchived - the archive set the durable document records.
|
|
94
|
+
* @throws DshRpcError when the Host is behind the document.
|
|
95
|
+
*/
|
|
96
|
+
assertRegistryFresh(documentArchived: readonly string[]): Promise<void>;
|
|
97
|
+
}
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Talking to a running DSH Host over its Typert RPC.
|
|
3
|
+
*
|
|
4
|
+
* The Host exposes its business services under `/api/<namespace>/<method>`
|
|
5
|
+
* with a JSON envelope. A browser session authenticates with a signed cookie;
|
|
6
|
+
* this module mints the same cookie from the local credential store, so the
|
|
7
|
+
* CLI acts as the Host's owner on the same machine that owns the Host.
|
|
8
|
+
*/
|
|
9
|
+
import { createHash, createHmac } from 'node:crypto';
|
|
10
|
+
import { readFileSync } from 'node:fs';
|
|
11
|
+
import { execFileSync } from 'node:child_process';
|
|
12
|
+
import { staleArchiveIds } from './dsh-registry-file.js';
|
|
13
|
+
/** The credential record holding the browser-session signing secret. */
|
|
14
|
+
const BROWSER_SESSION_RECORD = 'client-connection/browser-session';
|
|
15
|
+
/** The cookie prefix the Host expects. */
|
|
16
|
+
const COOKIE_PREFIX = 'dsh-auth-';
|
|
17
|
+
/** Cookie lifetime the CLI mints. */
|
|
18
|
+
const COOKIE_LIFETIME_MS = 24 * 60 * 60 * 1000;
|
|
19
|
+
/**
|
|
20
|
+
* The id the CLI passes when it only wants the registry's current sets.
|
|
21
|
+
*
|
|
22
|
+
* Session ids are UUIDs or `session-<uuid>` forms, so this can never name a
|
|
23
|
+
* real session; `unarchiveSession` and `unpinSession` therefore return the
|
|
24
|
+
* complete sets without changing anything.
|
|
25
|
+
*/
|
|
26
|
+
const REGISTRY_PROBE_ID = 'acp-service-cli-registry-probe';
|
|
27
|
+
/** An RPC failure reported by the Host. */
|
|
28
|
+
export class DshRpcError extends Error {
|
|
29
|
+
code;
|
|
30
|
+
constructor(code, message) {
|
|
31
|
+
super(message);
|
|
32
|
+
this.code = code;
|
|
33
|
+
this.name = 'DshRpcError';
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
const base64url = (bytes) => bytes.toString('base64').replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');
|
|
37
|
+
/**
|
|
38
|
+
* Read the browser-session signing secret from the local credential store.
|
|
39
|
+
*
|
|
40
|
+
* The store is a YAML document; this reads the one field it needs rather than
|
|
41
|
+
* taking a YAML dependency, and never returns the secret to the caller.
|
|
42
|
+
*
|
|
43
|
+
* @param credentialsPath - path to the credential document.
|
|
44
|
+
* @returns the signing secret.
|
|
45
|
+
*/
|
|
46
|
+
export function readBrowserSessionSecret(credentialsPath) {
|
|
47
|
+
let text;
|
|
48
|
+
try {
|
|
49
|
+
text = readFileSync(credentialsPath, 'utf8');
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
throw new Error(`cannot read ${credentialsPath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
53
|
+
}
|
|
54
|
+
const start = text.indexOf(BROWSER_SESSION_RECORD);
|
|
55
|
+
if (start < 0)
|
|
56
|
+
throw new Error(`${credentialsPath} has no ${BROWSER_SESSION_RECORD} record`);
|
|
57
|
+
const secret = text.slice(start, start + 2048).match(/secret:\s*([A-Za-z0-9_-]+)/);
|
|
58
|
+
if (!secret)
|
|
59
|
+
throw new Error(`${credentialsPath} has no browser-session secret`);
|
|
60
|
+
return Buffer.from(secret[1], 'base64url');
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Mint the signed browser-session cookie for one authority.
|
|
64
|
+
*
|
|
65
|
+
* @param secret - the signing secret from the credential store.
|
|
66
|
+
* @param authority - the host:port the cookie is scoped to.
|
|
67
|
+
* @returns the cookie header value.
|
|
68
|
+
*/
|
|
69
|
+
export function mintSessionCookie(secret, authority) {
|
|
70
|
+
const issuedAt = Date.now();
|
|
71
|
+
const payload = { version: 1, authority, issuedAt, expiresAt: issuedAt + COOKIE_LIFETIME_MS };
|
|
72
|
+
const body = base64url(Buffer.from(JSON.stringify(payload), 'utf8'));
|
|
73
|
+
const signature = base64url(createHmac('sha256', secret).update(body).digest());
|
|
74
|
+
const name = COOKIE_PREFIX + createHash('sha256').update(authority).digest('base64url');
|
|
75
|
+
return `${name}=v1.${body}.${signature}`;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* List the loopback TCP ports this machine is listening on.
|
|
79
|
+
*
|
|
80
|
+
* The desktop app binds an ephemeral port, so the CLI discovers the Host by
|
|
81
|
+
* probing local listeners rather than by a configured address.
|
|
82
|
+
*
|
|
83
|
+
* @returns the loopback ports, ascending.
|
|
84
|
+
*/
|
|
85
|
+
export function listLoopbackPorts() {
|
|
86
|
+
let output = '';
|
|
87
|
+
try {
|
|
88
|
+
output = execFileSync('lsof', ['-nP', '-iTCP', '-sTCP:LISTEN'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
return [];
|
|
92
|
+
}
|
|
93
|
+
const ports = new Set();
|
|
94
|
+
for (const line of output.split('\n').slice(1)) {
|
|
95
|
+
// The NAME column holds the bound address, such as `127.0.0.1:51971` or
|
|
96
|
+
// `*:51971`, followed by the connection state.
|
|
97
|
+
const match = line.match(/TCP\s+\S*?:(\d+)\s+\(LISTEN\)\s*$/);
|
|
98
|
+
if (!match)
|
|
99
|
+
continue;
|
|
100
|
+
const port = Number.parseInt(match[1], 10);
|
|
101
|
+
if (Number.isInteger(port) && port > 0)
|
|
102
|
+
ports.add(port);
|
|
103
|
+
}
|
|
104
|
+
return [...ports].sort((left, right) => left - right);
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Ask one origin whether it is a DSH Host that answers the session API.
|
|
108
|
+
*
|
|
109
|
+
* @param origin - the origin to probe.
|
|
110
|
+
* @param cookie - the minted cookie for that origin's authority.
|
|
111
|
+
* @returns whether the origin answered a session list.
|
|
112
|
+
*/
|
|
113
|
+
export async function probeHost(origin, cookie) {
|
|
114
|
+
try {
|
|
115
|
+
const response = await fetch(`${origin}/api/session/list`, {
|
|
116
|
+
method: 'POST',
|
|
117
|
+
headers: { 'content-type': 'application/json', cookie },
|
|
118
|
+
body: JSON.stringify({ type: 'client-request', rpcId: 'probe', method: 'session/list', payload: { args: { _request: {} } } }),
|
|
119
|
+
signal: AbortSignal.timeout(5_000),
|
|
120
|
+
});
|
|
121
|
+
if (!response.ok)
|
|
122
|
+
return false;
|
|
123
|
+
const body = await response.json();
|
|
124
|
+
return body?.result?.ok === true;
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
return false;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Find a reachable DSH Host.
|
|
132
|
+
*
|
|
133
|
+
* An explicit origin is authoritative: the CLI uses the first named origin
|
|
134
|
+
* that answers, so a caller can target one instance on purpose. Without one
|
|
135
|
+
* the CLI probes the machine's loopback listeners, because the desktop app
|
|
136
|
+
* binds an ephemeral port that nothing else records; there it prefers a Host
|
|
137
|
+
* whose registry already holds every archived id, since two Hosts can share
|
|
138
|
+
* one DSH home and the older one's copy would drop the newer archives on its
|
|
139
|
+
* next write.
|
|
140
|
+
*
|
|
141
|
+
* @param origins - explicit origins from the command line.
|
|
142
|
+
* @param secret - the browser-session signing secret.
|
|
143
|
+
* @param documentArchived - archive ids the durable document records, when known.
|
|
144
|
+
* @returns the chosen origin.
|
|
145
|
+
*/
|
|
146
|
+
export async function discoverHost(origins, secret, documentArchived) {
|
|
147
|
+
const explicit = [];
|
|
148
|
+
for (const origin of origins) {
|
|
149
|
+
const normalized = origin.replace(/\/+$/, '');
|
|
150
|
+
if (!explicit.includes(normalized))
|
|
151
|
+
explicit.push(normalized);
|
|
152
|
+
}
|
|
153
|
+
const probe = async (origin) => {
|
|
154
|
+
const authority = new URL(origin).host;
|
|
155
|
+
return await probeHost(origin, mintSessionCookie(secret, authority)) ? { origin, authority } : undefined;
|
|
156
|
+
};
|
|
157
|
+
if (explicit.length > 0) {
|
|
158
|
+
for (const origin of explicit) {
|
|
159
|
+
const endpoint = await probe(origin);
|
|
160
|
+
if (endpoint)
|
|
161
|
+
return endpoint;
|
|
162
|
+
}
|
|
163
|
+
throw new Error(`none of the given --url origins answered as a DSH Host: ${explicit.join(', ')}`);
|
|
164
|
+
}
|
|
165
|
+
const candidates = listLoopbackPorts().map(port => `http://127.0.0.1:${port}`);
|
|
166
|
+
const answering = [];
|
|
167
|
+
// Probe in small batches so one unresponsive listener cannot stall discovery.
|
|
168
|
+
for (let index = 0; index < candidates.length; index += 8) {
|
|
169
|
+
const batch = candidates.slice(index, index + 8);
|
|
170
|
+
const results = await Promise.all(batch.map(probe));
|
|
171
|
+
for (const result of results)
|
|
172
|
+
if (result)
|
|
173
|
+
answering.push(result);
|
|
174
|
+
}
|
|
175
|
+
if (answering.length === 0) {
|
|
176
|
+
throw new Error(`no reachable DSH Host found (tried ${candidates.length} local endpoint(s)); pass --url with the Host origin`);
|
|
177
|
+
}
|
|
178
|
+
if (documentArchived === undefined || documentArchived.length === 0)
|
|
179
|
+
return answering[0];
|
|
180
|
+
for (const endpoint of answering) {
|
|
181
|
+
const client = new DshHostClient(endpoint, mintSessionCookie(secret, endpoint.authority));
|
|
182
|
+
try {
|
|
183
|
+
const registry = await client.readRegistry();
|
|
184
|
+
if (staleArchiveIds(registry.archivedSessionIds, documentArchived).length === 0)
|
|
185
|
+
return endpoint;
|
|
186
|
+
}
|
|
187
|
+
catch {
|
|
188
|
+
// A Host that cannot report its registry is not preferred, but it still
|
|
189
|
+
// answered; it stays in the fallback set.
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
return answering[0];
|
|
193
|
+
}
|
|
194
|
+
/** A live DSH Host reached over RPC. */
|
|
195
|
+
export class DshHostClient {
|
|
196
|
+
endpoint;
|
|
197
|
+
cookie;
|
|
198
|
+
rpcId = 0;
|
|
199
|
+
/** The archive set this Host most recently reported, for the freshness check. */
|
|
200
|
+
lastArchivedSessionIds = [];
|
|
201
|
+
constructor(endpoint, cookie) {
|
|
202
|
+
this.endpoint = endpoint;
|
|
203
|
+
this.cookie = cookie;
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Call one Host method.
|
|
207
|
+
*
|
|
208
|
+
* @param method - the `namespace/method` endpoint.
|
|
209
|
+
* @param args - the method's arguments.
|
|
210
|
+
* @returns the decoded result value.
|
|
211
|
+
*/
|
|
212
|
+
async call(method, args) {
|
|
213
|
+
this.rpcId += 1;
|
|
214
|
+
const response = await fetch(`${this.endpoint.origin}/api/${method}`, {
|
|
215
|
+
method: 'POST',
|
|
216
|
+
headers: { 'content-type': 'application/json', cookie: this.cookie },
|
|
217
|
+
body: JSON.stringify({
|
|
218
|
+
type: 'client-request',
|
|
219
|
+
rpcId: `acp-service-${this.rpcId}`,
|
|
220
|
+
method,
|
|
221
|
+
payload: { args },
|
|
222
|
+
}),
|
|
223
|
+
signal: AbortSignal.timeout(60_000),
|
|
224
|
+
});
|
|
225
|
+
if (!response.ok)
|
|
226
|
+
throw new DshRpcError(`http/${response.status}`, `${method} returned HTTP ${response.status}`);
|
|
227
|
+
const body = await response.json();
|
|
228
|
+
if (body?.result?.ok !== true) {
|
|
229
|
+
const error = body?.result?.error;
|
|
230
|
+
throw new DshRpcError(error?.code ?? 'gateway/unknown', error?.message ?? `${method} failed`);
|
|
231
|
+
}
|
|
232
|
+
return body.result.value;
|
|
233
|
+
}
|
|
234
|
+
async listSessions() {
|
|
235
|
+
const value = await this.call('session/list', { _request: {} });
|
|
236
|
+
return value.items ?? [];
|
|
237
|
+
}
|
|
238
|
+
async readRegistry() {
|
|
239
|
+
// `unarchiveSession` and `unpinSession` are documented no-ops for an id
|
|
240
|
+
// that is not in the set, and each returns the complete resulting set.
|
|
241
|
+
// The sentinel is not a session id, so neither call can change anything.
|
|
242
|
+
const archived = await this.call('workspace/unarchiveSession', {
|
|
243
|
+
request: { sessionId: REGISTRY_PROBE_ID },
|
|
244
|
+
});
|
|
245
|
+
const pinned = await this.call('workspace/unpinSession', {
|
|
246
|
+
request: { sessionId: REGISTRY_PROBE_ID },
|
|
247
|
+
});
|
|
248
|
+
this.lastArchivedSessionIds = archived.archivedSessionIds ?? [];
|
|
249
|
+
return {
|
|
250
|
+
archivedSessionIds: this.lastArchivedSessionIds,
|
|
251
|
+
pinnedSessionIds: pinned.pinnedSessionIds ?? [],
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
async archiveSession(sessionId, options) {
|
|
255
|
+
await this.call('workspace/archiveSession', { request: { sessionId, stopActivity: options.stopActivity } });
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Refuse to write through a Host whose registry is behind the document.
|
|
259
|
+
*
|
|
260
|
+
* The Host holds the registry in memory and rewrites the whole document on
|
|
261
|
+
* every change, so a Host that started before another Host wrote the
|
|
262
|
+
* document would drop the newer archive entries. The command reports this
|
|
263
|
+
* instead of silently undoing someone else's archives.
|
|
264
|
+
*
|
|
265
|
+
* @param documentArchived - the archive set the durable document records.
|
|
266
|
+
* @throws DshRpcError when the Host is behind the document.
|
|
267
|
+
*/
|
|
268
|
+
async assertRegistryFresh(documentArchived) {
|
|
269
|
+
const stale = staleArchiveIds(this.lastArchivedSessionIds, documentArchived);
|
|
270
|
+
if (stale.length > 0) {
|
|
271
|
+
throw new DshRpcError('dsh/registry-stale', `this DSH instance is behind the durable registry: it is missing ${stale.length} archived session(s) that are recorded on disk. `
|
|
272
|
+
+ 'Restart this DSH instance so it reloads the registry, then run the command again.');
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** The archive and pin sets as the document records them. */
|
|
2
|
+
export interface RegistryFileState {
|
|
3
|
+
readonly archivedSessionIds: readonly string[];
|
|
4
|
+
readonly pinnedSessionIds: readonly string[];
|
|
5
|
+
/** Whether the document was read at all. */
|
|
6
|
+
readonly found: boolean;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Read the durable registry document.
|
|
10
|
+
*
|
|
11
|
+
* @param dshHome - the DSH home directory.
|
|
12
|
+
* @returns the recorded sets, or an empty result when the document is absent.
|
|
13
|
+
*/
|
|
14
|
+
export declare function readRegistryFile(dshHome: string): Promise<RegistryFileState>;
|
|
15
|
+
/**
|
|
16
|
+
* How far a Host's registry is behind the durable document.
|
|
17
|
+
*
|
|
18
|
+
* @param hostArchived - the archive set the running Host reported.
|
|
19
|
+
* @param fileArchived - the archive set the document records.
|
|
20
|
+
* @returns the ids the document holds and the Host does not.
|
|
21
|
+
*/
|
|
22
|
+
export declare function staleArchiveIds(hostArchived: readonly string[], fileArchived: readonly string[]): string[];
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reading the durable workspace registry from disk.
|
|
3
|
+
*
|
|
4
|
+
* The registry keeps its state in memory inside the running Host and writes
|
|
5
|
+
* the whole document on every change. When two Hosts share one DSH home — a
|
|
6
|
+
* `dsh web` instance and the desktop app, for example — the older one keeps a
|
|
7
|
+
* stale copy and would overwrite the newer one's archive set on its next
|
|
8
|
+
* write. The document on disk is therefore the record the CLI plans against,
|
|
9
|
+
* and the Host's own copy is checked against it before anything is written.
|
|
10
|
+
*/
|
|
11
|
+
import { readFile } from 'node:fs/promises';
|
|
12
|
+
import { join } from 'node:path';
|
|
13
|
+
/** The registry document the workspace domain stores. */
|
|
14
|
+
const REGISTRY_FILENAME = 'workspace.json';
|
|
15
|
+
/**
|
|
16
|
+
* Read the durable registry document.
|
|
17
|
+
*
|
|
18
|
+
* @param dshHome - the DSH home directory.
|
|
19
|
+
* @returns the recorded sets, or an empty result when the document is absent.
|
|
20
|
+
*/
|
|
21
|
+
export async function readRegistryFile(dshHome) {
|
|
22
|
+
const empty = { archivedSessionIds: [], pinnedSessionIds: [], found: false };
|
|
23
|
+
let text;
|
|
24
|
+
try {
|
|
25
|
+
text = await readFile(join(dshHome, 'storages', REGISTRY_FILENAME), 'utf8');
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return empty;
|
|
29
|
+
}
|
|
30
|
+
try {
|
|
31
|
+
const document = JSON.parse(text);
|
|
32
|
+
const archived = document.global?.archivedSessionIds;
|
|
33
|
+
const pinned = document.global?.pinnedSessionIds;
|
|
34
|
+
return {
|
|
35
|
+
archivedSessionIds: Array.isArray(archived) ? archived.filter((id) => typeof id === 'string') : [],
|
|
36
|
+
pinnedSessionIds: Array.isArray(pinned) ? pinned.filter((id) => typeof id === 'string') : [],
|
|
37
|
+
found: true,
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
// A document that cannot be parsed is not a basis for a write decision.
|
|
42
|
+
return empty;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* How far a Host's registry is behind the durable document.
|
|
47
|
+
*
|
|
48
|
+
* @param hostArchived - the archive set the running Host reported.
|
|
49
|
+
* @param fileArchived - the archive set the document records.
|
|
50
|
+
* @returns the ids the document holds and the Host does not.
|
|
51
|
+
*/
|
|
52
|
+
export function staleArchiveIds(hostArchived, fileArchived) {
|
|
53
|
+
const host = new Set(hostArchived);
|
|
54
|
+
return fileArchived.filter(id => !host.has(id));
|
|
55
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Collect the newest modification time of every stored session.
|
|
3
|
+
*
|
|
4
|
+
* @param sessionsRoot - the directory holding one subdirectory per working directory.
|
|
5
|
+
* @returns modification times by session id, in epoch milliseconds.
|
|
6
|
+
*/
|
|
7
|
+
export declare function readSessionFileMtimes(sessionsRoot: string): Promise<Map<string, number>>;
|