@stackstackstack/dsh-commands 0.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.i18n.yaml +6 -0
- package/README.md +40 -0
- package/README.zh.md +40 -0
- package/lib/index.js +360 -0
- package/lib/invariant.js +43 -0
- package/lib/typert.host.d.ts +3 -0
- package/lib/typert.host.js +502 -0
- package/lib/typert.remote-client.d.ts +29 -0
- package/lib/typert.remote-client.js +103 -0
- package/lib/types/brand.d.ts +25 -0
- package/lib/types/brand.js +20 -0
- package/lib/types/index.d.ts +126 -0
- package/lib/types/index.js +343 -0
- package/lib/types/invariant.d.ts +17 -0
- package/lib/types/invariant.js +60 -0
- package/lib/types/types.d.ts +102 -0
- package/lib/types/types.js +10 -0
- package/package.json +76 -0
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-commands' owned branded id: command lifecycle pairing across the
|
|
3
|
+
* session log, the wire admission response, and client-side flow pairing.
|
|
4
|
+
*
|
|
5
|
+
* The `Branded<B>` primitive lives in `@stackstackstack/dsh-brand`; this module
|
|
6
|
+
* is a pure type/constructor outlet (no cordis imports, no module
|
|
7
|
+
* augmentation) so wire and client programs can name the brand without
|
|
8
|
+
* loading the host plugin's Context merges — the `dsh-llm/brand` shape.
|
|
9
|
+
*
|
|
10
|
+
* @module @stackstackstack/dsh-commands/brand
|
|
11
|
+
*/
|
|
12
|
+
import type { Branded } from '@stackstackstack/dsh-brand';
|
|
13
|
+
/**
|
|
14
|
+
* Pairs one command execution's `command/run`/`command/done` lifecycle
|
|
15
|
+
* records with each other and with the `command.execute` admission response.
|
|
16
|
+
* Minted by the executor, monotonic per service instance.
|
|
17
|
+
*/
|
|
18
|
+
export type CommandId = Branded<'CommandId'>;
|
|
19
|
+
/**
|
|
20
|
+
* Brand a string as a {@link CommandId}.
|
|
21
|
+
* @param id - the executor-minted pairing id.
|
|
22
|
+
* @returns the same string, branded; no validation is performed.
|
|
23
|
+
*/
|
|
24
|
+
export declare function CommandId(id: string): CommandId;
|
|
25
|
+
//# sourceMappingURL=brand.d.ts.map
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-commands' owned branded id: command lifecycle pairing across the
|
|
3
|
+
* session log, the wire admission response, and client-side flow pairing.
|
|
4
|
+
*
|
|
5
|
+
* The `Branded<B>` primitive lives in `@stackstackstack/dsh-brand`; this module
|
|
6
|
+
* is a pure type/constructor outlet (no cordis imports, no module
|
|
7
|
+
* augmentation) so wire and client programs can name the brand without
|
|
8
|
+
* loading the host plugin's Context merges — the `dsh-llm/brand` shape.
|
|
9
|
+
*
|
|
10
|
+
* @module @stackstackstack/dsh-commands/brand
|
|
11
|
+
*/
|
|
12
|
+
/**
|
|
13
|
+
* Brand a string as a {@link CommandId}.
|
|
14
|
+
* @param id - the executor-minted pairing id.
|
|
15
|
+
* @returns the same string, branded; no validation is performed.
|
|
16
|
+
*/
|
|
17
|
+
export function CommandId(id) {
|
|
18
|
+
return id;
|
|
19
|
+
}
|
|
20
|
+
//# sourceMappingURL=brand.js.map
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Plugin-owned human-command registry shared by interactive UI adapters.
|
|
3
|
+
* @module @stackstackstack/dsh-commands
|
|
4
|
+
*/
|
|
5
|
+
import { Context } from '@deepseek-ai/cordis';
|
|
6
|
+
import type { Agent } from '@stackstackstack/dsh-agent';
|
|
7
|
+
import { TypertRemoteService } from '@stackstackstack/dsh-typert-protocol';
|
|
8
|
+
import { CommandId } from './brand.ts';
|
|
9
|
+
import type { CommandDescriptor, CommandExecution, CommandInputDescriptor, CommandResult } from './types.ts';
|
|
10
|
+
export { CommandId } from './brand.ts';
|
|
11
|
+
export type * from './types.ts';
|
|
12
|
+
export declare const name = "commands";
|
|
13
|
+
/** Invocation passed to one registered command handler. */
|
|
14
|
+
export interface CommandInvocation {
|
|
15
|
+
/** Pairing id already written to this invocation's `command/run` event. */
|
|
16
|
+
readonly commandId: CommandId;
|
|
17
|
+
/** Exact agent whose UI received the command. */
|
|
18
|
+
readonly agent: Agent;
|
|
19
|
+
/** Exact text following the registered command name, including separator whitespace. */
|
|
20
|
+
readonly rawInput: string;
|
|
21
|
+
/** Cancellation signal owned by the dispatching UI request. */
|
|
22
|
+
readonly signal: AbortSignal;
|
|
23
|
+
}
|
|
24
|
+
/** Plugin-owned command registration. */
|
|
25
|
+
export interface CommandDefinition {
|
|
26
|
+
/** Lowercase command name without the leading slash. */
|
|
27
|
+
readonly name: string;
|
|
28
|
+
/** Human-readable summary used in discovery UI. */
|
|
29
|
+
readonly description: string;
|
|
30
|
+
/** Optional free-form input hint advertised to capable clients. */
|
|
31
|
+
readonly input?: CommandInputDescriptor;
|
|
32
|
+
/**
|
|
33
|
+
* Whether `command/run` records `rawInput`. Defaults to true. A command
|
|
34
|
+
* whose domain event owns the payload sets this false to avoid duplicating
|
|
35
|
+
* that payload in the session log.
|
|
36
|
+
*/
|
|
37
|
+
readonly recordInput?: boolean;
|
|
38
|
+
/** Execute against the receiving agent without sending the command to the model. */
|
|
39
|
+
readonly handler: (invocation: CommandInvocation) => CommandResult | Promise<CommandResult>;
|
|
40
|
+
}
|
|
41
|
+
/** Syntactically valid slash command before registry resolution. */
|
|
42
|
+
export interface ParsedCommand {
|
|
43
|
+
/** Lowercase command name without the leading slash. */
|
|
44
|
+
readonly name: string;
|
|
45
|
+
/** Exact text following the command name. */
|
|
46
|
+
readonly rawInput: string;
|
|
47
|
+
}
|
|
48
|
+
declare module '@deepseek-ai/cordis' {
|
|
49
|
+
interface Context {
|
|
50
|
+
commands: CommandRuntime;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Parse an exact slash command without normalizing its trailing input.
|
|
55
|
+
*
|
|
56
|
+
* @param line - Complete candidate command line.
|
|
57
|
+
* @returns The parsed command, or `undefined` when the line is not a command.
|
|
58
|
+
*/
|
|
59
|
+
export declare function parseCommand(line: string): ParsedCommand | undefined;
|
|
60
|
+
/**
|
|
61
|
+
* Human-command registry. Plain-context definitions are global; definitions
|
|
62
|
+
* registered through a command-injected child of an agent context shadow
|
|
63
|
+
* globals for that agent.
|
|
64
|
+
*/
|
|
65
|
+
export declare class CommandRuntime extends TypertRemoteService {
|
|
66
|
+
private readonly layers;
|
|
67
|
+
/** Monotonic per-instance counter behind {@link mintCommandId}. */
|
|
68
|
+
private commandSeq;
|
|
69
|
+
/** Instance token keeping minted ids unique across process restarts over one resumed log. */
|
|
70
|
+
private readonly instanceToken;
|
|
71
|
+
constructor(ctx: Context);
|
|
72
|
+
/**
|
|
73
|
+
* Register a global or calling-agent-scoped command.
|
|
74
|
+
* @param definition - discovery metadata and direct UI handler.
|
|
75
|
+
* @returns the exact effect disposer that unregisters this definition.
|
|
76
|
+
*/
|
|
77
|
+
register(definition: CommandDefinition): () => void;
|
|
78
|
+
/**
|
|
79
|
+
* List the effective immutable command descriptors for one agent.
|
|
80
|
+
* @param agent - exact receiving agent and scoped-layer key.
|
|
81
|
+
* @returns name-sorted descriptors after scoped shadowing.
|
|
82
|
+
*/
|
|
83
|
+
list(agent: Agent): readonly CommandDescriptor[];
|
|
84
|
+
/**
|
|
85
|
+
* Resolve one effective command definition.
|
|
86
|
+
* @param agent - exact receiving agent and scoped-layer key.
|
|
87
|
+
* @param name - command name without a slash.
|
|
88
|
+
* @returns the scoped shadow or global definition.
|
|
89
|
+
*/
|
|
90
|
+
find(agent: Agent, name: string): CommandDefinition | undefined;
|
|
91
|
+
/**
|
|
92
|
+
* Parse and execute a known command without sending it to the model.
|
|
93
|
+
*
|
|
94
|
+
* A resolved command's lifecycle is logged: `command/run` is appended
|
|
95
|
+
* before the handler is invoked and `command/done` after settlement (a
|
|
96
|
+
* thrown or aborted handler settles as `kind: 'error'`). Both are direct
|
|
97
|
+
* log-only appends — no turn wraps them, and persistence drains them at
|
|
98
|
+
* ordinary checkpoints. Admission misses (syntax or unknown name) log
|
|
99
|
+
* nothing — they never entered a handler. A `command/run` append failure
|
|
100
|
+
* fails the execution loud; a `command/done` append failure on the
|
|
101
|
+
* handler-failure path is contained so the handler's own error stays the
|
|
102
|
+
* reported failure.
|
|
103
|
+
*
|
|
104
|
+
* @param agent - exact receiving agent.
|
|
105
|
+
* @param line - complete slash-command line.
|
|
106
|
+
* @param signal - cancellation signal owned by the UI request.
|
|
107
|
+
* @returns the settled execution (result + lifecycle pairing id), or
|
|
108
|
+
* `undefined` when syntax or name does not resolve.
|
|
109
|
+
*/
|
|
110
|
+
execute(agent: Agent, line: string, signal: AbortSignal): Promise<CommandExecution | undefined>;
|
|
111
|
+
/** Mint the next pairing id (monotonic; instance-token-prefixed so a resumed log never repeats one). */
|
|
112
|
+
private mintCommandId;
|
|
113
|
+
/**
|
|
114
|
+
* Append one log-only lifecycle event directly: no turn is opened for it and
|
|
115
|
+
* no flush is forced — persistence observes the eager `session/event` path
|
|
116
|
+
* and drains at ordinary checkpoints and teardown, like every other
|
|
117
|
+
* standalone plugin event.
|
|
118
|
+
*/
|
|
119
|
+
private appendLifecycle;
|
|
120
|
+
/** Resolve global definitions followed by exact scoped shadows. */
|
|
121
|
+
private view;
|
|
122
|
+
/** Notify every registry observer without making UI refresh load-bearing. */
|
|
123
|
+
private notifyChange;
|
|
124
|
+
}
|
|
125
|
+
export default CommandRuntime;
|
|
126
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Plugin-owned human-command registry shared by interactive UI adapters.
|
|
3
|
+
* @module @stackstackstack/dsh-commands
|
|
4
|
+
*/
|
|
5
|
+
var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
|
|
6
|
+
var useValue = arguments.length > 2;
|
|
7
|
+
for (var i = 0; i < initializers.length; i++) {
|
|
8
|
+
value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
|
|
9
|
+
}
|
|
10
|
+
return useValue ? value : void 0;
|
|
11
|
+
};
|
|
12
|
+
var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
|
|
13
|
+
function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
|
|
14
|
+
var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
|
|
15
|
+
var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
|
|
16
|
+
var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
|
|
17
|
+
var _, done = false;
|
|
18
|
+
for (var i = decorators.length - 1; i >= 0; i--) {
|
|
19
|
+
var context = {};
|
|
20
|
+
for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
|
|
21
|
+
for (var p in contextIn.access) context.access[p] = contextIn.access[p];
|
|
22
|
+
context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
|
|
23
|
+
var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
|
|
24
|
+
if (kind === "accessor") {
|
|
25
|
+
if (result === void 0) continue;
|
|
26
|
+
if (result === null || typeof result !== "object") throw new TypeError("Object expected");
|
|
27
|
+
if (_ = accept(result.get)) descriptor.get = _;
|
|
28
|
+
if (_ = accept(result.set)) descriptor.set = _;
|
|
29
|
+
if (_ = accept(result.init)) initializers.unshift(_);
|
|
30
|
+
}
|
|
31
|
+
else if (_ = accept(result)) {
|
|
32
|
+
if (kind === "field") initializers.unshift(_);
|
|
33
|
+
else descriptor[key] = _;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
if (target) Object.defineProperty(target, contextIn.name, descriptor);
|
|
37
|
+
done = true;
|
|
38
|
+
};
|
|
39
|
+
import { NamedEntries, ScopedLayers } from '@stackstackstack/dsh-scope';
|
|
40
|
+
import { TypertRemoteService, Remote } from '@stackstackstack/dsh-typert-protocol';
|
|
41
|
+
import { CommandId } from "./brand.js";
|
|
42
|
+
export { CommandId } from "./brand.js";
|
|
43
|
+
export const name = 'commands';
|
|
44
|
+
const COMMAND_NAME = /^[a-z][a-z0-9_-]*$/u;
|
|
45
|
+
/** All command registrations owned by one global or scoped layer. */
|
|
46
|
+
class CommandLayer {
|
|
47
|
+
commands;
|
|
48
|
+
/**
|
|
49
|
+
* Create one command layer with diagnostics specific to its ownership scope.
|
|
50
|
+
* @param scope - the scoped owner, or `undefined` for global registrations.
|
|
51
|
+
*/
|
|
52
|
+
constructor(scope) {
|
|
53
|
+
this.commands = new NamedEntries(name => new Error(scope === undefined
|
|
54
|
+
? `command "${name}" is already registered (for a per-agent variant, mount a command-injected plugin under that agent's \`agent.ctx\`)`
|
|
55
|
+
: `command "${name}" is already registered in this scope`));
|
|
56
|
+
}
|
|
57
|
+
/** @returns whether this layer owns no command registrations. */
|
|
58
|
+
isEmpty() {
|
|
59
|
+
return this.commands.isEmpty();
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Parse an exact slash command without normalizing its trailing input.
|
|
64
|
+
*
|
|
65
|
+
* @param line - Complete candidate command line.
|
|
66
|
+
* @returns The parsed command, or `undefined` when the line is not a command.
|
|
67
|
+
*/
|
|
68
|
+
export function parseCommand(line) {
|
|
69
|
+
const match = /^\/([a-z][a-z0-9_-]*)(?=$|[\t\n\r ])/u.exec(line);
|
|
70
|
+
if (match === null)
|
|
71
|
+
return undefined;
|
|
72
|
+
const name = match[1];
|
|
73
|
+
/* v8 ignore next -- the first capture is required whenever the regular expression matches */
|
|
74
|
+
if (name === undefined)
|
|
75
|
+
return undefined;
|
|
76
|
+
return Object.freeze({ name, rawInput: line.slice(match[0].length) });
|
|
77
|
+
}
|
|
78
|
+
/** Convert arbitrary abort reasons to one stable rejected Error. */
|
|
79
|
+
function abortError(signal) {
|
|
80
|
+
if (signal.reason instanceof Error)
|
|
81
|
+
return signal.reason;
|
|
82
|
+
return new Error(typeof signal.reason === 'string' ? signal.reason : 'command aborted');
|
|
83
|
+
}
|
|
84
|
+
/** Render arbitrary thrown values without trusting their string coercion. */
|
|
85
|
+
function renderThrown(value) {
|
|
86
|
+
try {
|
|
87
|
+
return String(value);
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
return '<unrenderable thrown value>';
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
/** Stop awaiting an uncooperative handler once its owning UI request aborts. */
|
|
94
|
+
function withAbort(promise, signal) {
|
|
95
|
+
if (signal.aborted)
|
|
96
|
+
return Promise.reject(abortError(signal));
|
|
97
|
+
return new Promise((resolve, reject) => {
|
|
98
|
+
const onAbort = () => {
|
|
99
|
+
signal.removeEventListener('abort', onAbort);
|
|
100
|
+
reject(abortError(signal));
|
|
101
|
+
};
|
|
102
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
103
|
+
promise.then((value) => {
|
|
104
|
+
signal.removeEventListener('abort', onAbort);
|
|
105
|
+
resolve(value);
|
|
106
|
+
}, (error) => {
|
|
107
|
+
signal.removeEventListener('abort', onAbort);
|
|
108
|
+
reject(error instanceof Error
|
|
109
|
+
? error
|
|
110
|
+
: new Error(`command handler rejected with a non-Error value: ${renderThrown(error)}`, { cause: error }));
|
|
111
|
+
});
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
/** Reject invalid command metadata before it can reach a UI protocol. */
|
|
115
|
+
function normalizeDefinition(definition) {
|
|
116
|
+
if (!COMMAND_NAME.test(definition.name)) {
|
|
117
|
+
throw new TypeError(`command name "${definition.name}" must match ${String(COMMAND_NAME)}`);
|
|
118
|
+
}
|
|
119
|
+
if (typeof definition.description !== 'string') {
|
|
120
|
+
throw new TypeError(`command "${definition.name}" description must be a string`);
|
|
121
|
+
}
|
|
122
|
+
if (definition.description.trim().length === 0) {
|
|
123
|
+
throw new TypeError(`command "${definition.name}" description must not be empty`);
|
|
124
|
+
}
|
|
125
|
+
if (typeof definition.handler !== 'function') {
|
|
126
|
+
throw new TypeError(`command "${definition.name}" handler must be a function`);
|
|
127
|
+
}
|
|
128
|
+
const rawInput = definition.input;
|
|
129
|
+
let input;
|
|
130
|
+
if (rawInput !== undefined) {
|
|
131
|
+
if (typeof rawInput !== 'object' || rawInput === null || !('hint' in rawInput)
|
|
132
|
+
|| typeof rawInput.hint !== 'string') {
|
|
133
|
+
throw new TypeError(`command "${definition.name}" input hint must be a string`);
|
|
134
|
+
}
|
|
135
|
+
if (rawInput.hint.trim().length === 0) {
|
|
136
|
+
throw new TypeError(`command "${definition.name}" input hint must not be empty`);
|
|
137
|
+
}
|
|
138
|
+
input = Object.freeze({ hint: rawInput.hint });
|
|
139
|
+
}
|
|
140
|
+
const normalized = Object.freeze({
|
|
141
|
+
name: definition.name,
|
|
142
|
+
description: definition.description,
|
|
143
|
+
...input === undefined ? {} : { input },
|
|
144
|
+
...definition.recordInput === undefined ? {} : { recordInput: definition.recordInput },
|
|
145
|
+
handler: definition.handler,
|
|
146
|
+
});
|
|
147
|
+
const descriptor = Object.freeze({
|
|
148
|
+
name: normalized.name,
|
|
149
|
+
description: normalized.description,
|
|
150
|
+
...normalized.input === undefined ? {} : { input: normalized.input },
|
|
151
|
+
});
|
|
152
|
+
return { definition: normalized, descriptor };
|
|
153
|
+
}
|
|
154
|
+
/** Validate and detach an untrusted handler result at the registry boundary. */
|
|
155
|
+
function normalizeResult(command, value) {
|
|
156
|
+
if (typeof value !== 'object' || value === null || !('kind' in value)) {
|
|
157
|
+
throw new TypeError(`command "${command}" handler must return a CommandResult`);
|
|
158
|
+
}
|
|
159
|
+
const result = value;
|
|
160
|
+
if (result.kind === 'success') {
|
|
161
|
+
if (result.text !== undefined && typeof result.text !== 'string') {
|
|
162
|
+
throw new TypeError(`command "${command}" success text must be a string when supplied`);
|
|
163
|
+
}
|
|
164
|
+
if (result.sourceEventSeq !== undefined
|
|
165
|
+
&& (!Number.isSafeInteger(result.sourceEventSeq) || result.sourceEventSeq < 0)) {
|
|
166
|
+
throw new TypeError(`command "${command}" success sourceEventSeq must be a non-negative safe integer when supplied`);
|
|
167
|
+
}
|
|
168
|
+
return Object.freeze({
|
|
169
|
+
kind: 'success',
|
|
170
|
+
...result.text === undefined ? {} : { text: result.text },
|
|
171
|
+
...result.sourceEventSeq === undefined ? {} : { sourceEventSeq: result.sourceEventSeq },
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
if (result.kind === 'error') {
|
|
175
|
+
if (typeof result.text !== 'string' || result.text.trim().length === 0) {
|
|
176
|
+
throw new TypeError(`command "${command}" error text must be a non-empty string`);
|
|
177
|
+
}
|
|
178
|
+
return Object.freeze({ kind: 'error', text: result.text });
|
|
179
|
+
}
|
|
180
|
+
throw new TypeError(`command "${command}" returned unknown result kind "${String(result.kind)}"`);
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Human-command registry. Plain-context definitions are global; definitions
|
|
184
|
+
* registered through a command-injected child of an agent context shadow
|
|
185
|
+
* globals for that agent.
|
|
186
|
+
*/
|
|
187
|
+
let CommandRuntime = (() => {
|
|
188
|
+
let _classSuper = TypertRemoteService;
|
|
189
|
+
let _instanceExtraInitializers = [];
|
|
190
|
+
let _list_decorators;
|
|
191
|
+
let _execute_decorators;
|
|
192
|
+
return class CommandRuntime extends _classSuper {
|
|
193
|
+
static {
|
|
194
|
+
const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
|
|
195
|
+
_list_decorators = [Remote];
|
|
196
|
+
_execute_decorators = [Remote];
|
|
197
|
+
__esDecorate(this, null, _list_decorators, { kind: "method", name: "list", static: false, private: false, access: { has: obj => "list" in obj, get: obj => obj.list }, metadata: _metadata }, null, _instanceExtraInitializers);
|
|
198
|
+
__esDecorate(this, null, _execute_decorators, { kind: "method", name: "execute", static: false, private: false, access: { has: obj => "execute" in obj, get: obj => obj.execute }, metadata: _metadata }, null, _instanceExtraInitializers);
|
|
199
|
+
if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
|
|
200
|
+
}
|
|
201
|
+
layers = (__runInitializers(this, _instanceExtraInitializers), new ScopedLayers(scope => new CommandLayer(scope), () => { this.notifyChange(); }));
|
|
202
|
+
/** Monotonic per-instance counter behind {@link mintCommandId}. */
|
|
203
|
+
commandSeq = 0;
|
|
204
|
+
/** Instance token keeping minted ids unique across process restarts over one resumed log. */
|
|
205
|
+
instanceToken = crypto.randomUUID().slice(0, 8);
|
|
206
|
+
constructor(ctx) {
|
|
207
|
+
super(ctx, 'commands');
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Register a global or calling-agent-scoped command.
|
|
211
|
+
* @param definition - discovery metadata and direct UI handler.
|
|
212
|
+
* @returns the exact effect disposer that unregisters this definition.
|
|
213
|
+
*/
|
|
214
|
+
register(definition) {
|
|
215
|
+
const registered = normalizeDefinition(definition);
|
|
216
|
+
return this.layers.effect(this.ctx, layer => layer.commands.insert(registered.definition.name, registered), { label: 'commands.register()' });
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* List the effective immutable command descriptors for one agent.
|
|
220
|
+
* @param agent - exact receiving agent and scoped-layer key.
|
|
221
|
+
* @returns name-sorted descriptors after scoped shadowing.
|
|
222
|
+
*/
|
|
223
|
+
list(agent) {
|
|
224
|
+
return Object.freeze([...this.view(agent).values()]
|
|
225
|
+
.map(command => command.descriptor)
|
|
226
|
+
// Names are unique in the effective view, so equality is impossible.
|
|
227
|
+
.sort((left, right) => left.name < right.name ? -1 : 1));
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Resolve one effective command definition.
|
|
231
|
+
* @param agent - exact receiving agent and scoped-layer key.
|
|
232
|
+
* @param name - command name without a slash.
|
|
233
|
+
* @returns the scoped shadow or global definition.
|
|
234
|
+
*/
|
|
235
|
+
find(agent, name) {
|
|
236
|
+
return this.view(agent).get(name)?.definition;
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Parse and execute a known command without sending it to the model.
|
|
240
|
+
*
|
|
241
|
+
* A resolved command's lifecycle is logged: `command/run` is appended
|
|
242
|
+
* before the handler is invoked and `command/done` after settlement (a
|
|
243
|
+
* thrown or aborted handler settles as `kind: 'error'`). Both are direct
|
|
244
|
+
* log-only appends — no turn wraps them, and persistence drains them at
|
|
245
|
+
* ordinary checkpoints. Admission misses (syntax or unknown name) log
|
|
246
|
+
* nothing — they never entered a handler. A `command/run` append failure
|
|
247
|
+
* fails the execution loud; a `command/done` append failure on the
|
|
248
|
+
* handler-failure path is contained so the handler's own error stays the
|
|
249
|
+
* reported failure.
|
|
250
|
+
*
|
|
251
|
+
* @param agent - exact receiving agent.
|
|
252
|
+
* @param line - complete slash-command line.
|
|
253
|
+
* @param signal - cancellation signal owned by the UI request.
|
|
254
|
+
* @returns the settled execution (result + lifecycle pairing id), or
|
|
255
|
+
* `undefined` when syntax or name does not resolve.
|
|
256
|
+
*/
|
|
257
|
+
async execute(agent, line, signal) {
|
|
258
|
+
const parsed = parseCommand(line);
|
|
259
|
+
if (parsed === undefined)
|
|
260
|
+
return undefined;
|
|
261
|
+
const command = this.view(agent).get(parsed.name);
|
|
262
|
+
if (command === undefined)
|
|
263
|
+
return undefined;
|
|
264
|
+
if (signal.aborted)
|
|
265
|
+
throw abortError(signal);
|
|
266
|
+
const commandId = this.mintCommandId();
|
|
267
|
+
this.appendLifecycle(agent.session, 'command/run', {
|
|
268
|
+
commandId,
|
|
269
|
+
name: parsed.name,
|
|
270
|
+
...command.definition.recordInput === false ? {} : { args: parsed.rawInput },
|
|
271
|
+
source: { kind: 'user' },
|
|
272
|
+
});
|
|
273
|
+
const invocation = Object.freeze({ commandId, agent, rawInput: parsed.rawInput, signal });
|
|
274
|
+
let result;
|
|
275
|
+
try {
|
|
276
|
+
const output = command.definition.handler(invocation);
|
|
277
|
+
result = normalizeResult(parsed.name, await withAbort(Promise.resolve(output), signal));
|
|
278
|
+
}
|
|
279
|
+
catch (error) {
|
|
280
|
+
try {
|
|
281
|
+
this.appendLifecycle(agent.session, 'command/done', {
|
|
282
|
+
commandId, kind: 'error',
|
|
283
|
+
text: error instanceof Error ? error.message : renderThrown(error),
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
catch (appendError) {
|
|
287
|
+
this.ctx.logger.warn(`command "${parsed.name}": command/done append failed: ${renderThrown(appendError)}`);
|
|
288
|
+
}
|
|
289
|
+
throw error;
|
|
290
|
+
}
|
|
291
|
+
this.appendLifecycle(agent.session, 'command/done', {
|
|
292
|
+
commandId, kind: result.kind,
|
|
293
|
+
...result.text === undefined ? {} : { text: result.text },
|
|
294
|
+
...result.kind === 'success' && result.sourceEventSeq !== undefined
|
|
295
|
+
? { sourceEventSeq: result.sourceEventSeq }
|
|
296
|
+
: {},
|
|
297
|
+
});
|
|
298
|
+
return Object.freeze({ commandId, result });
|
|
299
|
+
}
|
|
300
|
+
/** Mint the next pairing id (monotonic; instance-token-prefixed so a resumed log never repeats one). */
|
|
301
|
+
mintCommandId() {
|
|
302
|
+
this.commandSeq += 1;
|
|
303
|
+
return CommandId(`cmd-${this.instanceToken}-${this.commandSeq}`);
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Append one log-only lifecycle event directly: no turn is opened for it and
|
|
307
|
+
* no flush is forced — persistence observes the eager `session/event` path
|
|
308
|
+
* and drains at ordinary checkpoints and teardown, like every other
|
|
309
|
+
* standalone plugin event.
|
|
310
|
+
*/
|
|
311
|
+
appendLifecycle(session, type, data) {
|
|
312
|
+
// Both admitted types are log-only (non-surface), but TypeScript does not
|
|
313
|
+
// reduce Session.append's conditional rest parameter through a generic
|
|
314
|
+
// type parameter. Preserve the proven two-argument call shape.
|
|
315
|
+
const appendLogOnly = session.append.bind(session);
|
|
316
|
+
return appendLogOnly(type, data);
|
|
317
|
+
}
|
|
318
|
+
/** Resolve global definitions followed by exact scoped shadows. */
|
|
319
|
+
view(agent) {
|
|
320
|
+
return this.layers.merge(agent, layer => layer.commands);
|
|
321
|
+
}
|
|
322
|
+
/** Notify every registry observer without making UI refresh load-bearing. */
|
|
323
|
+
notifyChange() {
|
|
324
|
+
// Cordis emit uses Array.map: one synchronous throw starves later listeners,
|
|
325
|
+
// and returned promises are discarded. Registry notifications are
|
|
326
|
+
// non-vetoing, so contain each callback independently.
|
|
327
|
+
for (const callback of this.ctx.events.dispatch('emit', ['commands/change'])) {
|
|
328
|
+
try {
|
|
329
|
+
const returned = callback();
|
|
330
|
+
void Promise.resolve(returned).catch((error) => {
|
|
331
|
+
this.ctx.logger.warn(`commands/change listener rejected: ${renderThrown(error)}`);
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
catch (error) {
|
|
335
|
+
this.ctx.logger.warn(`commands/change listener threw: ${renderThrown(error)}`);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
};
|
|
340
|
+
})();
|
|
341
|
+
export { CommandRuntime };
|
|
342
|
+
export default CommandRuntime;
|
|
343
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Package-owned invariant companion for `@stackstackstack/dsh-commands`:
|
|
3
|
+
* command lifecycle events pair by commandId within one session log.
|
|
4
|
+
* @module @stackstackstack/dsh-commands/invariant
|
|
5
|
+
*/
|
|
6
|
+
import type { Context } from '@deepseek-ai/cordis';
|
|
7
|
+
/** Cordis companion plugin name. */
|
|
8
|
+
export declare const name = "commands-invariant";
|
|
9
|
+
/** Service required before the companion can reserve package ownership. */
|
|
10
|
+
export declare const inject: string[];
|
|
11
|
+
/**
|
|
12
|
+
* Register this package's invariant companion.
|
|
13
|
+
* @param ctx - Cordis context carrying the invariant service.
|
|
14
|
+
* @returns the installed registration's disposer after setup succeeds.
|
|
15
|
+
*/
|
|
16
|
+
export declare const apply: (ctx: Context) => Promise<() => void>;
|
|
17
|
+
//# sourceMappingURL=invariant.d.ts.map
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Package-owned invariant companion for `@stackstackstack/dsh-commands`:
|
|
3
|
+
* command lifecycle events pair by commandId within one session log.
|
|
4
|
+
* @module @stackstackstack/dsh-commands/invariant
|
|
5
|
+
*/
|
|
6
|
+
const PACKAGE_NAME = '@stackstackstack/dsh-commands';
|
|
7
|
+
/** Cordis companion plugin name. */
|
|
8
|
+
export const name = 'commands-invariant';
|
|
9
|
+
/** Service required before the companion can reserve package ownership. */
|
|
10
|
+
export const inject = ['invariants'];
|
|
11
|
+
/* jscpd:ignore-start -- package companions share replay and dispatch plumbing */
|
|
12
|
+
/** Install pairing validation over loaded logs and newly appended lifecycle events. */
|
|
13
|
+
const install = Object.assign((ctx, fail) => {
|
|
14
|
+
// Install-scoped so a dispose/re-register cycle re-sweeps from a clean slate.
|
|
15
|
+
const runIds = new WeakMap();
|
|
16
|
+
const validateEvent = (session, event) => {
|
|
17
|
+
if (event.type === 'command/run') {
|
|
18
|
+
const ids = runIds.get(session) ?? new Set();
|
|
19
|
+
if (ids.has(event.data.commandId)) {
|
|
20
|
+
fail(`command/run repeats commandId ${JSON.stringify(event.data.commandId)}`);
|
|
21
|
+
}
|
|
22
|
+
ids.add(event.data.commandId);
|
|
23
|
+
runIds.set(session, ids);
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
if (event.type !== 'command/done')
|
|
27
|
+
return;
|
|
28
|
+
if (runIds.get(session)?.has(event.data.commandId) !== true) {
|
|
29
|
+
fail(`command/done ${JSON.stringify(event.data.commandId)} pairs no prior command/run in this log`);
|
|
30
|
+
}
|
|
31
|
+
const source = event.data.sourceEventSeq;
|
|
32
|
+
const sourceEvent = source === undefined ? undefined : session.events[source];
|
|
33
|
+
if (source !== undefined
|
|
34
|
+
&& (event.data.kind !== 'success'
|
|
35
|
+
|| !Number.isSafeInteger(source) || source < 0 || source >= event.seq
|
|
36
|
+
|| sourceEvent?.seq !== source
|
|
37
|
+
|| sourceEvent.type === 'command/run'
|
|
38
|
+
|| sourceEvent.type === 'command/done')) {
|
|
39
|
+
fail(`command/done ${JSON.stringify(event.data.commandId)} has invalid sourceEventSeq ${String(source)}`);
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
for (const session of ctx.sessions.list()) {
|
|
43
|
+
for (const event of session.events)
|
|
44
|
+
validateEvent(session, event);
|
|
45
|
+
}
|
|
46
|
+
ctx.on('internal/dispatch', (_mode, eventName, args) => {
|
|
47
|
+
if (eventName !== 'session/event')
|
|
48
|
+
return;
|
|
49
|
+
const [session, event] = args;
|
|
50
|
+
validateEvent(session, event);
|
|
51
|
+
}, { global: true });
|
|
52
|
+
}, { inject: ['sessions'] });
|
|
53
|
+
/* jscpd:ignore-end */
|
|
54
|
+
/**
|
|
55
|
+
* Register this package's invariant companion.
|
|
56
|
+
* @param ctx - Cordis context carrying the invariant service.
|
|
57
|
+
* @returns the installed registration's disposer after setup succeeds.
|
|
58
|
+
*/
|
|
59
|
+
export const apply = (ctx) => Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install));
|
|
60
|
+
//# sourceMappingURL=invariant.js.map
|