@canonmsg/backend-contracts 8.2.0 → 8.4.0

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/dist/cjs/index.js CHANGED
@@ -35,3 +35,5 @@ __exportStar(require("./firestoreValues.js"), exports);
35
35
  __exportStar(require("./moderation.js"), exports);
36
36
  __exportStar(require("./selfContext.js"), exports);
37
37
  __exportStar(require("./replyAuthority.js"), exports);
38
+ __exportStar(require("./runtimeDescriptor.js"), exports);
39
+ __exportStar(require("./workSessions.js"), exports);
@@ -0,0 +1,184 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MAX_PUBLIC_RUNTIME_COMMANDS = void 0;
4
+ exports.normalizeRuntimeCommandAlias = normalizeRuntimeCommandAlias;
5
+ exports.normalizeRuntimeCommandAliases = normalizeRuntimeCommandAliases;
6
+ exports.isRuntimePrimitiveId = isRuntimePrimitiveId;
7
+ exports.normalizePublicRuntimeCommands = normalizePublicRuntimeCommands;
8
+ exports.normalizePublicRuntimeDescriptor = normalizePublicRuntimeDescriptor;
9
+ exports.normalizePublicRuntimeFacts = normalizePublicRuntimeFacts;
10
+ function normalizeRuntimeCommandAlias(value) {
11
+ const normalized = value.trim().replace(/^\/+/, '').replace(/\s+/g, '-');
12
+ return /^[A-Za-z0-9:_-]+$/.test(normalized) ? normalized : null;
13
+ }
14
+ function normalizeRuntimeCommandAliases(command) {
15
+ const rawAliases = command.aliases?.length ? command.aliases : [command.id];
16
+ const aliases = rawAliases
17
+ .map(normalizeRuntimeCommandAlias)
18
+ .filter((value) => Boolean(value));
19
+ return Array.from(new Set(aliases));
20
+ }
21
+ exports.MAX_PUBLIC_RUNTIME_COMMANDS = 256;
22
+ function record(value) {
23
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
24
+ ? value : {};
25
+ }
26
+ function text(value, max) {
27
+ return typeof value === 'string' && value.length > 0 && value.length <= max ? value : undefined;
28
+ }
29
+ function member(value, choices) {
30
+ return choices.includes(value) ? value : undefined;
31
+ }
32
+ function members(value, choices) {
33
+ if (!Array.isArray(value))
34
+ return undefined;
35
+ return [...new Set(value.filter((entry) => choices.includes(entry)))];
36
+ }
37
+ function defined(value) {
38
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined));
39
+ }
40
+ const PRIMITIVES = [
41
+ 'runtime.status', 'runtime.reasoning.set', 'runtime.verbosity.set', 'runtime.usage',
42
+ 'context.compact', 'session.new', 'session.reset',
43
+ ];
44
+ function isRuntimePrimitiveId(value) {
45
+ return typeof value === 'string' && PRIMITIVES.includes(value);
46
+ }
47
+ function normalizeDispatch(value) {
48
+ const dispatch = record(value);
49
+ switch (dispatch.kind) {
50
+ case 'signal': {
51
+ const signal = member(dispatch.signal, ['interrupt', 'stop_and_drop', 'new_session']);
52
+ return signal ? { kind: 'signal', signal } : undefined;
53
+ }
54
+ case 'primitive': {
55
+ const primitive = member(dispatch.primitive, PRIMITIVES);
56
+ return primitive ? { kind: 'primitive', primitive } : undefined;
57
+ }
58
+ case 'control': {
59
+ const controlId = text(dispatch.controlId, 128);
60
+ return controlId ? defined({ kind: 'control', controlId, value: text(dispatch.value, 1024) }) : undefined;
61
+ }
62
+ case 'text_passthrough': {
63
+ const template = text(dispatch.template, 2048);
64
+ return template ? { kind: 'text_passthrough', template } : undefined;
65
+ }
66
+ case 'compose': {
67
+ const content = text(dispatch.text, 2048);
68
+ return content ? { kind: 'compose', text: content } : undefined;
69
+ }
70
+ case 'open_details':
71
+ return defined({ kind: 'open_details', target: text(dispatch.target, 128) });
72
+ default:
73
+ return undefined;
74
+ }
75
+ }
76
+ function normalizeArgument(value) {
77
+ const arg = record(value);
78
+ const id = text(arg.id, 128);
79
+ const label = text(arg.label, 160);
80
+ const kind = member(arg.kind, ['string', 'enum', 'boolean']);
81
+ if (!id || !label || !kind)
82
+ return undefined;
83
+ if (['required', 'captureRemaining'].some((key) => arg[key] !== undefined && typeof arg[key] !== 'boolean'))
84
+ return undefined;
85
+ if (arg.choices !== undefined && !Array.isArray(arg.choices))
86
+ return undefined;
87
+ const choices = Array.isArray(arg.choices) ? arg.choices.slice(0, 128).flatMap((value) => {
88
+ const choice = record(value);
89
+ const entry = text(choice.value, 1024);
90
+ const label = text(choice.label, 160);
91
+ return entry && label ? [defined({ value: entry, label, description: text(choice.description, 1024) })] : [];
92
+ }) : undefined;
93
+ // Do not advertise an argument whose required enum has no usable choices.
94
+ if (kind === 'enum' && !choices?.length)
95
+ return undefined;
96
+ return defined({ id, label, kind, choices,
97
+ required: typeof arg.required === 'boolean' ? arg.required : undefined,
98
+ captureRemaining: typeof arg.captureRemaining === 'boolean' ? arg.captureRemaining : undefined,
99
+ });
100
+ }
101
+ /** Public command metadata shared by REST and direct RTDB publishers. Never copies local configuration. */
102
+ function normalizePublicRuntimeCommands(value) {
103
+ if (!Array.isArray(value))
104
+ return [];
105
+ const seenIds = new Set();
106
+ const seenAliases = new Set();
107
+ const result = [];
108
+ for (const item of value.slice(0, exports.MAX_PUBLIC_RUNTIME_COMMANDS)) {
109
+ const command = record(item);
110
+ const id = text(command.id, 128);
111
+ const label = text(command.label, 160);
112
+ const dispatch = normalizeDispatch(command.dispatch);
113
+ if (!id || !label || !dispatch || seenIds.has(id)
114
+ || command.visibility === 'hidden' || command.sensitive === true)
115
+ continue;
116
+ if (['ownerOnly', 'sensitive'].some((key) => command[key] !== undefined && typeof command[key] !== 'boolean'))
117
+ continue;
118
+ if (['aliases', 'args', 'placements', 'availability'].some((key) => command[key] !== undefined && !Array.isArray(command[key])))
119
+ continue;
120
+ const rawAliases = Array.isArray(command.aliases) && command.aliases.length ? command.aliases : [id];
121
+ const aliases = [...new Set(rawAliases.slice(0, 8).flatMap((value) => {
122
+ const alias = typeof value === 'string' && value.length <= 128 ? normalizeRuntimeCommandAlias(value) : null;
123
+ return alias && /^[A-Za-z0-9:_-]+$/.test(alias) && !seenAliases.has(alias.toLowerCase()) ? [alias] : [];
124
+ }))];
125
+ if (!aliases.length)
126
+ continue;
127
+ const args = Array.isArray(command.args) ? command.args.slice(0, 12).map(normalizeArgument) : undefined;
128
+ // A malformed argument must not silently turn a parameterized action into a different command.
129
+ if (args?.some((arg) => !arg) || (Array.isArray(command.args) && command.args.length > 12))
130
+ continue;
131
+ seenIds.add(id);
132
+ aliases.forEach((alias) => seenAliases.add(alias.toLowerCase()));
133
+ result.push(defined({ id, label, aliases, dispatch,
134
+ args: args,
135
+ description: text(command.description, 1024),
136
+ category: member(command.category, ['plan', 'turn', 'session', 'runtime', 'details', 'skill', 'custom']),
137
+ placements: members(command.placements, ['composer_slash', 'command_palette', 'session_strip']),
138
+ availability: members(command.availability, ['idle', 'busy', 'busy_with_queue', 'waiting_input', 'always']),
139
+ ownerOnly: typeof command.ownerOnly === 'boolean' ? command.ownerOnly : undefined,
140
+ disabledReason: text(command.disabledReason, 1024),
141
+ trailingTextBehavior: member(command.trailingTextBehavior, ['ignore', 'send_as_prompt']),
142
+ primitive: member(command.primitive, PRIMITIVES),
143
+ tier: member(command.tier, ['primary', 'detail', 'diagnostic']),
144
+ }));
145
+ }
146
+ return result;
147
+ }
148
+ function normalizePublicRuntimeDescriptor(value) {
149
+ const descriptor = record(value);
150
+ return defined({
151
+ supportsInterrupt: typeof descriptor.supportsInterrupt === 'boolean' ? descriptor.supportsInterrupt : undefined,
152
+ supportsInputInterrupt: typeof descriptor.supportsInputInterrupt === 'boolean' ? descriptor.supportsInputInterrupt : undefined,
153
+ streamingTextMode: member(descriptor.streamingTextMode, ['none', 'status', 'snapshot', 'block', 'delta']),
154
+ commands: Array.isArray(descriptor.commands) ? normalizePublicRuntimeCommands(descriptor.commands) : undefined,
155
+ });
156
+ }
157
+ const PUBLIC_RUNTIME_FACT_GROUPS = {
158
+ harness: 'runtime', runtime: 'runtime', provider: 'model', model: 'model',
159
+ reasoning: 'model', connection: 'connection', gateway: 'connection', route: 'route',
160
+ };
161
+ /** Read-only session facts, excluding local paths, inventories, and hidden/sensitive values. */
162
+ function normalizePublicRuntimeFacts(value) {
163
+ if (!Array.isArray(value))
164
+ return [];
165
+ const seen = new Set();
166
+ return value.slice(0, 16).flatMap((entry) => {
167
+ const fact = record(entry);
168
+ const id = text(fact.id, 64);
169
+ const group = id && Object.hasOwn(PUBLIC_RUNTIME_FACT_GROUPS, id)
170
+ ? PUBLIC_RUNTIME_FACT_GROUPS[id] : undefined;
171
+ const label = text(fact.label, 80);
172
+ const content = text(fact.value, 512);
173
+ if (!id || !group || !label || !content || seen.has(id)
174
+ || fact.sensitive === true || fact.visibility === 'hidden')
175
+ return [];
176
+ seen.add(id);
177
+ return [defined({ id, group, label, value: content,
178
+ tier: member(fact.tier, ['primary', 'detail', 'diagnostic']),
179
+ tone: member(fact.tone, ['neutral', 'good', 'warning', 'danger']),
180
+ copyable: typeof fact.copyable === 'boolean' ? fact.copyable : undefined,
181
+ updatedAt: typeof fact.updatedAt === 'number' && Number.isFinite(fact.updatedAt) && fact.updatedAt >= 0
182
+ ? fact.updatedAt : undefined, })];
183
+ });
184
+ }
@@ -0,0 +1,162 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WORK_SESSION_REQUEST_TTL_MS = exports.WORK_SESSION_LEASE_MS = exports.WORK_SESSION_SCHEMA = void 0;
4
+ exports.workSessionId = workSessionId;
5
+ exports.parseWorkSessionSettings = parseWorkSessionSettings;
6
+ exports.parseWorkSessionCatalog = parseWorkSessionCatalog;
7
+ exports.parseWorkSessionSelection = parseWorkSessionSelection;
8
+ exports.assertWorkSessionSelectionAvailable = assertWorkSessionSelectionAvailable;
9
+ exports.parseWorkSessionRuntimeRegistration = parseWorkSessionRuntimeRegistration;
10
+ exports.parseWorkSessionRuntimeAuth = parseWorkSessionRuntimeAuth;
11
+ exports.parseRequestWorkSessionInput = parseRequestWorkSessionInput;
12
+ exports.parseWorkSessionCompletion = parseWorkSessionCompletion;
13
+ /** Private owner/operator workflow. None of this catalog belongs in public runtime descriptors. */
14
+ exports.WORK_SESSION_SCHEMA = 'canon.work-sessions.v1';
15
+ exports.WORK_SESSION_LEASE_MS = 90_000;
16
+ exports.WORK_SESSION_REQUEST_TTL_MS = 5 * 60_000;
17
+ const SETTINGS_KEYS = ['projectId', 'modelId', 'reasoningEffort', 'permissionMode', 'executionMode'];
18
+ function object(value, keys, label) {
19
+ if (!value || typeof value !== 'object' || Array.isArray(value))
20
+ throw new Error(`Invalid ${label}`);
21
+ const result = value;
22
+ if (Object.keys(result).some((key) => !keys.includes(key)))
23
+ throw new Error(`Unsupported ${label} field`);
24
+ return result;
25
+ }
26
+ function workSessionId(value, label = 'identifier') {
27
+ if (typeof value !== 'string' || !/^[A-Za-z0-9_.:-]{1,160}$/.test(value))
28
+ throw new Error(`Invalid ${label}`);
29
+ return value;
30
+ }
31
+ function label(value, name, max = 160) {
32
+ if (typeof value !== 'string' || !value.trim() || value.length > max)
33
+ throw new Error(`Invalid ${name}`);
34
+ return value.trim();
35
+ }
36
+ function parseWorkSessionSettings(value) {
37
+ const input = object(value, SETTINGS_KEYS, 'settings');
38
+ return Object.fromEntries(Object.entries(input).map(([key, value]) => [key, workSessionId(value, key)]));
39
+ }
40
+ function choices(value, models = false) {
41
+ if (!Array.isArray(value) || value.length > 128)
42
+ throw new Error('Invalid choices');
43
+ const ids = new Set();
44
+ return value.map((entry) => {
45
+ const input = object(entry, ['id', 'label', 'description', ...(models ? ['reasoningEfforts', 'defaultReasoningEffort'] : [])], 'choice');
46
+ const id = workSessionId(input.id);
47
+ if (ids.has(id))
48
+ throw new Error('Duplicate choice identifier');
49
+ ids.add(id);
50
+ const result = { id, label: label(input.label, 'choice label') };
51
+ if (input.description !== undefined)
52
+ result.description = label(input.description, 'choice description', 512);
53
+ if (input.reasoningEfforts !== undefined)
54
+ result.reasoningEfforts = choices(input.reasoningEfforts);
55
+ if (input.defaultReasoningEffort !== undefined) {
56
+ result.defaultReasoningEffort = workSessionId(input.defaultReasoningEffort);
57
+ if (!result.reasoningEfforts?.some((choice) => choice.id === result.defaultReasoningEffort))
58
+ throw new Error('Invalid default reasoning effort');
59
+ }
60
+ return result;
61
+ });
62
+ }
63
+ function parseWorkSessionCatalog(value) {
64
+ const input = object(value, ['revision', 'provider', 'canCreate', 'canAttach', 'projects', 'models', 'reasoningEfforts', 'permissionModes', 'executionModes', 'defaults', 'sessions'], 'catalog');
65
+ if (typeof input.canCreate !== 'boolean' || typeof input.canAttach !== 'boolean')
66
+ throw new Error('Invalid catalog capabilities');
67
+ if (!Array.isArray(input.sessions) || input.sessions.length > 128)
68
+ throw new Error('Invalid loaded sessions');
69
+ const ids = new Set();
70
+ const result = {
71
+ revision: workSessionId(input.revision, 'catalog revision'), provider: workSessionId(input.provider, 'provider'),
72
+ canCreate: input.canCreate, canAttach: input.canAttach, projects: choices(input.projects),
73
+ sessions: input.sessions.map((entry) => {
74
+ const session = object(entry, ['id', 'title', 'status', 'settings', 'projectLabel', 'modelLabel'], 'loaded session');
75
+ const id = workSessionId(session.id, 'session identifier');
76
+ if (ids.has(id))
77
+ throw new Error('Duplicate loaded session');
78
+ ids.add(id);
79
+ if (session.status !== 'idle' && session.status !== 'running')
80
+ throw new Error('Invalid session status');
81
+ return {
82
+ id, title: label(session.title, 'session title'), status: session.status,
83
+ settings: parseWorkSessionSettings(session.settings),
84
+ ...(session.projectLabel !== undefined ? { projectLabel: label(session.projectLabel, 'project label') } : {}),
85
+ ...(session.modelLabel !== undefined ? { modelLabel: label(session.modelLabel, 'model label') } : {}),
86
+ };
87
+ }),
88
+ };
89
+ for (const key of ['models', 'reasoningEfforts', 'permissionModes', 'executionModes']) {
90
+ if (input[key] !== undefined)
91
+ result[key] = choices(input[key], key === 'models');
92
+ }
93
+ if (input.defaults !== undefined)
94
+ result.defaults = parseWorkSessionSettings(input.defaults);
95
+ if (result.canCreate && !result.projects.length)
96
+ throw new Error('Creating sessions requires an advertised project');
97
+ if (JSON.stringify(result).length > 65_536)
98
+ throw new Error('Work session catalog is too large');
99
+ return result;
100
+ }
101
+ function parseWorkSessionSelection(value) {
102
+ const mode = value?.mode;
103
+ if (mode === 'attach') {
104
+ const input = object(value, ['mode', 'sessionId'], 'attach selection');
105
+ return { mode, sessionId: workSessionId(input.sessionId, 'session identifier') };
106
+ }
107
+ if (mode === 'create') {
108
+ const { mode: _mode, ...settings } = object(value, ['mode', ...SETTINGS_KEYS], 'create selection');
109
+ return { mode, ...parseWorkSessionSettings(settings), projectId: workSessionId(settings.projectId, 'project identifier') };
110
+ }
111
+ throw new Error('Invalid work session selection');
112
+ }
113
+ function assertWorkSessionSelectionAvailable(selection, catalog) {
114
+ if (selection.mode === 'attach') {
115
+ if (!catalog.canAttach || !catalog.sessions.some((session) => session.id === selection.sessionId))
116
+ throw new Error('Selected loaded session is unavailable');
117
+ return;
118
+ }
119
+ if (!catalog.canCreate || !catalog.projects.some((project) => project.id === selection.projectId))
120
+ throw new Error('Selected project is unavailable');
121
+ const modelId = selection.modelId ?? catalog.defaults?.modelId;
122
+ const model = catalog.models?.find((choice) => choice.id === modelId);
123
+ const available = {
124
+ modelId: catalog.models, reasoningEffort: model?.reasoningEfforts ?? catalog.reasoningEfforts,
125
+ permissionMode: catalog.permissionModes, executionMode: catalog.executionModes,
126
+ };
127
+ for (const key of ['modelId', 'reasoningEffort', 'permissionMode', 'executionMode']) {
128
+ if (selection[key] !== undefined && !available[key]?.some((choice) => choice.id === selection[key]))
129
+ throw new Error(`Selected ${key} is unavailable`);
130
+ }
131
+ }
132
+ function parseWorkSessionRuntimeRegistration(value) {
133
+ const input = object(value, ['hostId', 'runtimeEpoch', 'displayName', 'catalog'], 'runtime registration');
134
+ return { hostId: workSessionId(input.hostId), runtimeEpoch: workSessionId(input.runtimeEpoch), displayName: label(input.displayName, 'host name'), catalog: parseWorkSessionCatalog(input.catalog) };
135
+ }
136
+ function parseWorkSessionRuntimeAuth(value, extraKeys = []) {
137
+ const input = object(value, ['hostId', 'runtimeEpoch', 'leaseToken', ...extraKeys], 'runtime request');
138
+ return { hostId: workSessionId(input.hostId), runtimeEpoch: workSessionId(input.runtimeEpoch), leaseToken: workSessionId(input.leaseToken, 'lease token') };
139
+ }
140
+ function parseRequestWorkSessionInput(value) {
141
+ const input = object(value, ['agentId', 'conversationId', 'requestId', 'hostId', 'runtimeEpoch', 'catalogRevision', 'selection'], 'work session request');
142
+ if (typeof input.requestId !== 'string' || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(input.requestId))
143
+ throw new Error('requestId must be a UUID');
144
+ return {
145
+ agentId: workSessionId(input.agentId), conversationId: workSessionId(input.conversationId), requestId: input.requestId,
146
+ hostId: workSessionId(input.hostId), runtimeEpoch: workSessionId(input.runtimeEpoch), catalogRevision: workSessionId(input.catalogRevision),
147
+ selection: parseWorkSessionSelection(input.selection),
148
+ };
149
+ }
150
+ function parseWorkSessionCompletion(value) {
151
+ const status = value?.status;
152
+ if (status === 'attached') {
153
+ const input = object(value, ['status', 'nativeSessionId', 'settings'], 'attached result');
154
+ return { status, nativeSessionId: workSessionId(input.nativeSessionId), settings: parseWorkSessionSettings(input.settings) };
155
+ }
156
+ if (status === 'failed' || status === 'uncertain') {
157
+ const input = object(value, ['status', 'error'], 'failure result');
158
+ const error = object(input.error, ['code', 'message'], 'failure');
159
+ return { status, error: { code: workSessionId(error.code), message: label(error.message, 'failure message', 512) } };
160
+ }
161
+ throw new Error('Invalid work session result');
162
+ }
package/dist/index.d.ts CHANGED
@@ -19,3 +19,5 @@ export * from './firestoreValues.js';
19
19
  export * from './moderation.js';
20
20
  export * from './selfContext.js';
21
21
  export * from './replyAuthority.js';
22
+ export * from './runtimeDescriptor.js';
23
+ export * from './workSessions.js';
package/dist/index.js CHANGED
@@ -19,3 +19,5 @@ export * from './firestoreValues.js';
19
19
  export * from './moderation.js';
20
20
  export * from './selfContext.js';
21
21
  export * from './replyAuthority.js';
22
+ export * from './runtimeDescriptor.js';
23
+ export * from './workSessions.js';
@@ -0,0 +1,88 @@
1
+ export type CanonControlValue = string;
2
+ export type CanonRuntimeStreamingMode = 'none' | 'status' | 'snapshot' | 'block' | 'delta';
3
+ export type CanonRuntimeDetailTier = 'primary' | 'detail' | 'diagnostic';
4
+ export type CanonRuntimeVisibility = 'conversation' | 'hidden';
5
+ export type CanonRuntimeActionAvailability = 'idle' | 'busy' | 'busy_with_queue' | 'waiting_input' | 'always';
6
+ export type CanonRuntimeActionPlacement = 'composer_slash' | 'command_palette' | 'session_strip';
7
+ export type CanonRuntimeActionCategory = 'plan' | 'turn' | 'session' | 'runtime' | 'details' | 'skill' | 'custom';
8
+ export type CanonRuntimePrimitiveId = 'runtime.status' | 'runtime.reasoning.set' | 'runtime.verbosity.set' | 'runtime.usage' | 'context.compact' | 'session.new' | 'session.reset';
9
+ export type CanonRuntimeCommandArgumentKind = 'string' | 'enum' | 'boolean';
10
+ export interface CanonRuntimeCommandArgumentChoice {
11
+ value: string;
12
+ label: string;
13
+ description?: string;
14
+ }
15
+ export interface CanonRuntimeCommandArgumentDescriptor {
16
+ id: string;
17
+ label: string;
18
+ kind: CanonRuntimeCommandArgumentKind;
19
+ required?: boolean;
20
+ captureRemaining?: boolean;
21
+ choices?: ReadonlyArray<CanonRuntimeCommandArgumentChoice>;
22
+ }
23
+ export type CanonRuntimeActionDispatch = {
24
+ kind: 'control';
25
+ controlId: string;
26
+ value?: CanonControlValue;
27
+ } | {
28
+ kind: 'signal';
29
+ signal: 'interrupt' | 'stop_and_drop' | 'new_session';
30
+ } | {
31
+ kind: 'primitive';
32
+ primitive: CanonRuntimePrimitiveId;
33
+ } | {
34
+ kind: 'text_passthrough';
35
+ template: string;
36
+ } | {
37
+ kind: 'compose';
38
+ text: string;
39
+ } | {
40
+ kind: 'open_details';
41
+ target?: string;
42
+ };
43
+ export interface CanonRuntimeActionDescriptor {
44
+ id: string;
45
+ label: string;
46
+ description?: string;
47
+ visibility?: CanonRuntimeVisibility;
48
+ tier?: CanonRuntimeDetailTier;
49
+ sensitive?: boolean;
50
+ primitive?: CanonRuntimePrimitiveId;
51
+ aliases?: ReadonlyArray<string>;
52
+ category?: CanonRuntimeActionCategory;
53
+ placements?: ReadonlyArray<CanonRuntimeActionPlacement>;
54
+ availability?: ReadonlyArray<CanonRuntimeActionAvailability>;
55
+ ownerOnly?: boolean;
56
+ disabledReason?: string | null;
57
+ trailingTextBehavior?: 'ignore' | 'send_as_prompt';
58
+ args?: ReadonlyArray<CanonRuntimeCommandArgumentDescriptor>;
59
+ dispatch: CanonRuntimeActionDispatch;
60
+ }
61
+ export interface CanonRuntimeCommandDescriptor extends CanonRuntimeActionDescriptor {
62
+ primitive?: CanonRuntimePrimitiveId;
63
+ args?: ReadonlyArray<CanonRuntimeCommandArgumentDescriptor>;
64
+ }
65
+ export declare function normalizeRuntimeCommandAlias(value: string): string | null;
66
+ export declare function normalizeRuntimeCommandAliases(command: Pick<CanonRuntimeCommandDescriptor, 'id' | 'aliases'>): string[];
67
+ export declare const MAX_PUBLIC_RUNTIME_COMMANDS = 256;
68
+ export declare function isRuntimePrimitiveId(value: unknown): value is CanonRuntimePrimitiveId;
69
+ /** Public command metadata shared by REST and direct RTDB publishers. Never copies local configuration. */
70
+ export declare function normalizePublicRuntimeCommands(value: unknown): CanonRuntimeCommandDescriptor[];
71
+ export interface PublicRuntimeDescriptor {
72
+ supportsInterrupt?: boolean;
73
+ supportsInputInterrupt?: boolean;
74
+ streamingTextMode?: CanonRuntimeStreamingMode;
75
+ commands?: CanonRuntimeCommandDescriptor[];
76
+ }
77
+ export declare function normalizePublicRuntimeDescriptor(value: unknown): PublicRuntimeDescriptor;
78
+ /** Read-only session facts, excluding local paths, inventories, and hidden/sensitive values. */
79
+ export declare function normalizePublicRuntimeFacts(value: unknown): {
80
+ id: string;
81
+ group: "runtime" | "model" | "connection" | "route";
82
+ label: string;
83
+ value: string;
84
+ tier: "primary" | "detail" | "diagnostic" | undefined;
85
+ tone: "neutral" | "good" | "warning" | "danger" | undefined;
86
+ copyable: boolean | undefined;
87
+ updatedAt: number | undefined;
88
+ }[];
@@ -0,0 +1,175 @@
1
+ export function normalizeRuntimeCommandAlias(value) {
2
+ const normalized = value.trim().replace(/^\/+/, '').replace(/\s+/g, '-');
3
+ return /^[A-Za-z0-9:_-]+$/.test(normalized) ? normalized : null;
4
+ }
5
+ export function normalizeRuntimeCommandAliases(command) {
6
+ const rawAliases = command.aliases?.length ? command.aliases : [command.id];
7
+ const aliases = rawAliases
8
+ .map(normalizeRuntimeCommandAlias)
9
+ .filter((value) => Boolean(value));
10
+ return Array.from(new Set(aliases));
11
+ }
12
+ export const MAX_PUBLIC_RUNTIME_COMMANDS = 256;
13
+ function record(value) {
14
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
15
+ ? value : {};
16
+ }
17
+ function text(value, max) {
18
+ return typeof value === 'string' && value.length > 0 && value.length <= max ? value : undefined;
19
+ }
20
+ function member(value, choices) {
21
+ return choices.includes(value) ? value : undefined;
22
+ }
23
+ function members(value, choices) {
24
+ if (!Array.isArray(value))
25
+ return undefined;
26
+ return [...new Set(value.filter((entry) => choices.includes(entry)))];
27
+ }
28
+ function defined(value) {
29
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined));
30
+ }
31
+ const PRIMITIVES = [
32
+ 'runtime.status', 'runtime.reasoning.set', 'runtime.verbosity.set', 'runtime.usage',
33
+ 'context.compact', 'session.new', 'session.reset',
34
+ ];
35
+ export function isRuntimePrimitiveId(value) {
36
+ return typeof value === 'string' && PRIMITIVES.includes(value);
37
+ }
38
+ function normalizeDispatch(value) {
39
+ const dispatch = record(value);
40
+ switch (dispatch.kind) {
41
+ case 'signal': {
42
+ const signal = member(dispatch.signal, ['interrupt', 'stop_and_drop', 'new_session']);
43
+ return signal ? { kind: 'signal', signal } : undefined;
44
+ }
45
+ case 'primitive': {
46
+ const primitive = member(dispatch.primitive, PRIMITIVES);
47
+ return primitive ? { kind: 'primitive', primitive } : undefined;
48
+ }
49
+ case 'control': {
50
+ const controlId = text(dispatch.controlId, 128);
51
+ return controlId ? defined({ kind: 'control', controlId, value: text(dispatch.value, 1024) }) : undefined;
52
+ }
53
+ case 'text_passthrough': {
54
+ const template = text(dispatch.template, 2048);
55
+ return template ? { kind: 'text_passthrough', template } : undefined;
56
+ }
57
+ case 'compose': {
58
+ const content = text(dispatch.text, 2048);
59
+ return content ? { kind: 'compose', text: content } : undefined;
60
+ }
61
+ case 'open_details':
62
+ return defined({ kind: 'open_details', target: text(dispatch.target, 128) });
63
+ default:
64
+ return undefined;
65
+ }
66
+ }
67
+ function normalizeArgument(value) {
68
+ const arg = record(value);
69
+ const id = text(arg.id, 128);
70
+ const label = text(arg.label, 160);
71
+ const kind = member(arg.kind, ['string', 'enum', 'boolean']);
72
+ if (!id || !label || !kind)
73
+ return undefined;
74
+ if (['required', 'captureRemaining'].some((key) => arg[key] !== undefined && typeof arg[key] !== 'boolean'))
75
+ return undefined;
76
+ if (arg.choices !== undefined && !Array.isArray(arg.choices))
77
+ return undefined;
78
+ const choices = Array.isArray(arg.choices) ? arg.choices.slice(0, 128).flatMap((value) => {
79
+ const choice = record(value);
80
+ const entry = text(choice.value, 1024);
81
+ const label = text(choice.label, 160);
82
+ return entry && label ? [defined({ value: entry, label, description: text(choice.description, 1024) })] : [];
83
+ }) : undefined;
84
+ // Do not advertise an argument whose required enum has no usable choices.
85
+ if (kind === 'enum' && !choices?.length)
86
+ return undefined;
87
+ return defined({ id, label, kind, choices,
88
+ required: typeof arg.required === 'boolean' ? arg.required : undefined,
89
+ captureRemaining: typeof arg.captureRemaining === 'boolean' ? arg.captureRemaining : undefined,
90
+ });
91
+ }
92
+ /** Public command metadata shared by REST and direct RTDB publishers. Never copies local configuration. */
93
+ export function normalizePublicRuntimeCommands(value) {
94
+ if (!Array.isArray(value))
95
+ return [];
96
+ const seenIds = new Set();
97
+ const seenAliases = new Set();
98
+ const result = [];
99
+ for (const item of value.slice(0, MAX_PUBLIC_RUNTIME_COMMANDS)) {
100
+ const command = record(item);
101
+ const id = text(command.id, 128);
102
+ const label = text(command.label, 160);
103
+ const dispatch = normalizeDispatch(command.dispatch);
104
+ if (!id || !label || !dispatch || seenIds.has(id)
105
+ || command.visibility === 'hidden' || command.sensitive === true)
106
+ continue;
107
+ if (['ownerOnly', 'sensitive'].some((key) => command[key] !== undefined && typeof command[key] !== 'boolean'))
108
+ continue;
109
+ if (['aliases', 'args', 'placements', 'availability'].some((key) => command[key] !== undefined && !Array.isArray(command[key])))
110
+ continue;
111
+ const rawAliases = Array.isArray(command.aliases) && command.aliases.length ? command.aliases : [id];
112
+ const aliases = [...new Set(rawAliases.slice(0, 8).flatMap((value) => {
113
+ const alias = typeof value === 'string' && value.length <= 128 ? normalizeRuntimeCommandAlias(value) : null;
114
+ return alias && /^[A-Za-z0-9:_-]+$/.test(alias) && !seenAliases.has(alias.toLowerCase()) ? [alias] : [];
115
+ }))];
116
+ if (!aliases.length)
117
+ continue;
118
+ const args = Array.isArray(command.args) ? command.args.slice(0, 12).map(normalizeArgument) : undefined;
119
+ // A malformed argument must not silently turn a parameterized action into a different command.
120
+ if (args?.some((arg) => !arg) || (Array.isArray(command.args) && command.args.length > 12))
121
+ continue;
122
+ seenIds.add(id);
123
+ aliases.forEach((alias) => seenAliases.add(alias.toLowerCase()));
124
+ result.push(defined({ id, label, aliases, dispatch,
125
+ args: args,
126
+ description: text(command.description, 1024),
127
+ category: member(command.category, ['plan', 'turn', 'session', 'runtime', 'details', 'skill', 'custom']),
128
+ placements: members(command.placements, ['composer_slash', 'command_palette', 'session_strip']),
129
+ availability: members(command.availability, ['idle', 'busy', 'busy_with_queue', 'waiting_input', 'always']),
130
+ ownerOnly: typeof command.ownerOnly === 'boolean' ? command.ownerOnly : undefined,
131
+ disabledReason: text(command.disabledReason, 1024),
132
+ trailingTextBehavior: member(command.trailingTextBehavior, ['ignore', 'send_as_prompt']),
133
+ primitive: member(command.primitive, PRIMITIVES),
134
+ tier: member(command.tier, ['primary', 'detail', 'diagnostic']),
135
+ }));
136
+ }
137
+ return result;
138
+ }
139
+ export function normalizePublicRuntimeDescriptor(value) {
140
+ const descriptor = record(value);
141
+ return defined({
142
+ supportsInterrupt: typeof descriptor.supportsInterrupt === 'boolean' ? descriptor.supportsInterrupt : undefined,
143
+ supportsInputInterrupt: typeof descriptor.supportsInputInterrupt === 'boolean' ? descriptor.supportsInputInterrupt : undefined,
144
+ streamingTextMode: member(descriptor.streamingTextMode, ['none', 'status', 'snapshot', 'block', 'delta']),
145
+ commands: Array.isArray(descriptor.commands) ? normalizePublicRuntimeCommands(descriptor.commands) : undefined,
146
+ });
147
+ }
148
+ const PUBLIC_RUNTIME_FACT_GROUPS = {
149
+ harness: 'runtime', runtime: 'runtime', provider: 'model', model: 'model',
150
+ reasoning: 'model', connection: 'connection', gateway: 'connection', route: 'route',
151
+ };
152
+ /** Read-only session facts, excluding local paths, inventories, and hidden/sensitive values. */
153
+ export function normalizePublicRuntimeFacts(value) {
154
+ if (!Array.isArray(value))
155
+ return [];
156
+ const seen = new Set();
157
+ return value.slice(0, 16).flatMap((entry) => {
158
+ const fact = record(entry);
159
+ const id = text(fact.id, 64);
160
+ const group = id && Object.hasOwn(PUBLIC_RUNTIME_FACT_GROUPS, id)
161
+ ? PUBLIC_RUNTIME_FACT_GROUPS[id] : undefined;
162
+ const label = text(fact.label, 80);
163
+ const content = text(fact.value, 512);
164
+ if (!id || !group || !label || !content || seen.has(id)
165
+ || fact.sensitive === true || fact.visibility === 'hidden')
166
+ return [];
167
+ seen.add(id);
168
+ return [defined({ id, group, label, value: content,
169
+ tier: member(fact.tier, ['primary', 'detail', 'diagnostic']),
170
+ tone: member(fact.tone, ['neutral', 'good', 'warning', 'danger']),
171
+ copyable: typeof fact.copyable === 'boolean' ? fact.copyable : undefined,
172
+ updatedAt: typeof fact.updatedAt === 'number' && Number.isFinite(fact.updatedAt) && fact.updatedAt >= 0
173
+ ? fact.updatedAt : undefined, })];
174
+ });
175
+ }
@@ -0,0 +1,156 @@
1
+ /** Private owner/operator workflow. None of this catalog belongs in public runtime descriptors. */
2
+ export declare const WORK_SESSION_SCHEMA: "canon.work-sessions.v1";
3
+ export declare const WORK_SESSION_LEASE_MS = 90000;
4
+ export declare const WORK_SESSION_REQUEST_TTL_MS: number;
5
+ export interface WorkSessionChoice {
6
+ id: string;
7
+ label: string;
8
+ description?: string;
9
+ }
10
+ export interface WorkSessionModelChoice extends WorkSessionChoice {
11
+ reasoningEfforts?: WorkSessionChoice[];
12
+ defaultReasoningEffort?: string;
13
+ }
14
+ export interface WorkSessionSettings {
15
+ projectId?: string;
16
+ modelId?: string;
17
+ reasoningEffort?: string;
18
+ permissionMode?: string;
19
+ executionMode?: string;
20
+ }
21
+ export type WorkSessionSelection = ({
22
+ mode: 'create';
23
+ projectId: string;
24
+ } & Omit<WorkSessionSettings, 'projectId'>) | {
25
+ mode: 'attach';
26
+ sessionId: string;
27
+ };
28
+ export interface WorkSessionLoadedSession {
29
+ id: string;
30
+ title: string;
31
+ status: 'idle' | 'running';
32
+ settings: WorkSessionSettings;
33
+ projectLabel?: string;
34
+ modelLabel?: string;
35
+ }
36
+ export interface WorkSessionCatalog {
37
+ revision: string;
38
+ provider: string;
39
+ canCreate: boolean;
40
+ canAttach: boolean;
41
+ projects: WorkSessionChoice[];
42
+ models?: WorkSessionModelChoice[];
43
+ reasoningEfforts?: WorkSessionChoice[];
44
+ permissionModes?: WorkSessionChoice[];
45
+ executionModes?: WorkSessionChoice[];
46
+ defaults?: WorkSessionSettings;
47
+ sessions: WorkSessionLoadedSession[];
48
+ }
49
+ export interface WorkSessionRuntimeIdentity {
50
+ hostId: string;
51
+ runtimeEpoch: string;
52
+ }
53
+ export interface WorkSessionRuntimeLease extends WorkSessionRuntimeIdentity {
54
+ /** Agent-only fencing credential. Never expose in the owner catalog or request status. */
55
+ leaseToken: string;
56
+ expiresAt: number;
57
+ }
58
+ export interface WorkSessionRuntimeRegistration extends WorkSessionRuntimeIdentity {
59
+ displayName: string;
60
+ catalog: WorkSessionCatalog;
61
+ }
62
+ export interface WorkSessionBinding {
63
+ workSessionId: string;
64
+ conversationId: string;
65
+ hostId: string;
66
+ provider: string;
67
+ nativeSessionId: string;
68
+ settings: WorkSessionSettings;
69
+ createdAt: number;
70
+ }
71
+ export interface WorkSessionRuntimeState {
72
+ ownerId: string;
73
+ lease: WorkSessionRuntimeLease;
74
+ bindings: WorkSessionBinding[];
75
+ }
76
+ export interface WorkSessionCatalogResult {
77
+ status: 'available' | 'offline' | 'unavailable';
78
+ agentId: string;
79
+ hostId?: string;
80
+ runtimeEpoch?: string;
81
+ displayName?: string;
82
+ expiresAt?: number;
83
+ catalog?: WorkSessionCatalog;
84
+ bindings: WorkSessionBinding[];
85
+ }
86
+ export interface RequestWorkSessionInput extends WorkSessionRuntimeIdentity {
87
+ agentId: string;
88
+ conversationId: string;
89
+ requestId: string;
90
+ catalogRevision: string;
91
+ selection: WorkSessionSelection;
92
+ }
93
+ export type WorkSessionRequestStatus = 'pending' | 'claimed' | 'attached' | 'failed' | 'uncertain' | 'expired';
94
+ export interface WorkSessionRequest extends RequestWorkSessionInput {
95
+ schema: typeof WORK_SESSION_SCHEMA;
96
+ requestedBy: string;
97
+ status: WorkSessionRequestStatus;
98
+ createdAt: number;
99
+ updatedAt: number;
100
+ expiresAt: number;
101
+ binding?: WorkSessionBinding;
102
+ error?: {
103
+ code: string;
104
+ message: string;
105
+ };
106
+ }
107
+ export type WorkSessionCompletion = {
108
+ status: 'attached';
109
+ nativeSessionId: string;
110
+ settings: WorkSessionSettings;
111
+ } | {
112
+ status: 'failed' | 'uncertain';
113
+ error: {
114
+ code: string;
115
+ message: string;
116
+ };
117
+ };
118
+ export type WorkSessionRuntimeAuth = Pick<WorkSessionRuntimeLease, 'hostId' | 'runtimeEpoch' | 'leaseToken'>;
119
+ export interface WorkSessionClaimInput extends WorkSessionRuntimeAuth {
120
+ requestId?: string;
121
+ }
122
+ export interface WorkSessionClaimResult {
123
+ request: WorkSessionRequest | null;
124
+ /** Previously claimed: reconcile the durable host journal, never blindly execute again. */
125
+ replayed: boolean;
126
+ }
127
+ export interface CompleteWorkSessionInput extends WorkSessionRuntimeAuth {
128
+ requestId: string;
129
+ result: WorkSessionCompletion;
130
+ }
131
+ export interface WorkSessionHeartbeatInput extends WorkSessionRuntimeAuth {
132
+ catalog?: WorkSessionCatalog;
133
+ }
134
+ export interface ReleaseWorkSessionBindingInput extends WorkSessionRuntimeAuth {
135
+ conversationId: string;
136
+ workSessionId: string;
137
+ }
138
+ export interface ResolveWorkSessionRequestInput {
139
+ agentId: string;
140
+ requestId: string;
141
+ }
142
+ export interface GetWorkSessionRequestInput {
143
+ agentId: string;
144
+ /** Exactly one selector. Conversation lookup recovers the latest operation after reload. */
145
+ requestId?: string;
146
+ conversationId?: string;
147
+ }
148
+ export declare function workSessionId(value: unknown, label?: string): string;
149
+ export declare function parseWorkSessionSettings(value: unknown): WorkSessionSettings;
150
+ export declare function parseWorkSessionCatalog(value: unknown): WorkSessionCatalog;
151
+ export declare function parseWorkSessionSelection(value: unknown): WorkSessionSelection;
152
+ export declare function assertWorkSessionSelectionAvailable(selection: WorkSessionSelection, catalog: WorkSessionCatalog): void;
153
+ export declare function parseWorkSessionRuntimeRegistration(value: unknown): WorkSessionRuntimeRegistration;
154
+ export declare function parseWorkSessionRuntimeAuth(value: unknown, extraKeys?: string[]): WorkSessionRuntimeAuth;
155
+ export declare function parseRequestWorkSessionInput(value: unknown): RequestWorkSessionInput;
156
+ export declare function parseWorkSessionCompletion(value: unknown): WorkSessionCompletion;
@@ -0,0 +1,150 @@
1
+ /** Private owner/operator workflow. None of this catalog belongs in public runtime descriptors. */
2
+ export const WORK_SESSION_SCHEMA = 'canon.work-sessions.v1';
3
+ export const WORK_SESSION_LEASE_MS = 90_000;
4
+ export const WORK_SESSION_REQUEST_TTL_MS = 5 * 60_000;
5
+ const SETTINGS_KEYS = ['projectId', 'modelId', 'reasoningEffort', 'permissionMode', 'executionMode'];
6
+ function object(value, keys, label) {
7
+ if (!value || typeof value !== 'object' || Array.isArray(value))
8
+ throw new Error(`Invalid ${label}`);
9
+ const result = value;
10
+ if (Object.keys(result).some((key) => !keys.includes(key)))
11
+ throw new Error(`Unsupported ${label} field`);
12
+ return result;
13
+ }
14
+ export function workSessionId(value, label = 'identifier') {
15
+ if (typeof value !== 'string' || !/^[A-Za-z0-9_.:-]{1,160}$/.test(value))
16
+ throw new Error(`Invalid ${label}`);
17
+ return value;
18
+ }
19
+ function label(value, name, max = 160) {
20
+ if (typeof value !== 'string' || !value.trim() || value.length > max)
21
+ throw new Error(`Invalid ${name}`);
22
+ return value.trim();
23
+ }
24
+ export function parseWorkSessionSettings(value) {
25
+ const input = object(value, SETTINGS_KEYS, 'settings');
26
+ return Object.fromEntries(Object.entries(input).map(([key, value]) => [key, workSessionId(value, key)]));
27
+ }
28
+ function choices(value, models = false) {
29
+ if (!Array.isArray(value) || value.length > 128)
30
+ throw new Error('Invalid choices');
31
+ const ids = new Set();
32
+ return value.map((entry) => {
33
+ const input = object(entry, ['id', 'label', 'description', ...(models ? ['reasoningEfforts', 'defaultReasoningEffort'] : [])], 'choice');
34
+ const id = workSessionId(input.id);
35
+ if (ids.has(id))
36
+ throw new Error('Duplicate choice identifier');
37
+ ids.add(id);
38
+ const result = { id, label: label(input.label, 'choice label') };
39
+ if (input.description !== undefined)
40
+ result.description = label(input.description, 'choice description', 512);
41
+ if (input.reasoningEfforts !== undefined)
42
+ result.reasoningEfforts = choices(input.reasoningEfforts);
43
+ if (input.defaultReasoningEffort !== undefined) {
44
+ result.defaultReasoningEffort = workSessionId(input.defaultReasoningEffort);
45
+ if (!result.reasoningEfforts?.some((choice) => choice.id === result.defaultReasoningEffort))
46
+ throw new Error('Invalid default reasoning effort');
47
+ }
48
+ return result;
49
+ });
50
+ }
51
+ export function parseWorkSessionCatalog(value) {
52
+ const input = object(value, ['revision', 'provider', 'canCreate', 'canAttach', 'projects', 'models', 'reasoningEfforts', 'permissionModes', 'executionModes', 'defaults', 'sessions'], 'catalog');
53
+ if (typeof input.canCreate !== 'boolean' || typeof input.canAttach !== 'boolean')
54
+ throw new Error('Invalid catalog capabilities');
55
+ if (!Array.isArray(input.sessions) || input.sessions.length > 128)
56
+ throw new Error('Invalid loaded sessions');
57
+ const ids = new Set();
58
+ const result = {
59
+ revision: workSessionId(input.revision, 'catalog revision'), provider: workSessionId(input.provider, 'provider'),
60
+ canCreate: input.canCreate, canAttach: input.canAttach, projects: choices(input.projects),
61
+ sessions: input.sessions.map((entry) => {
62
+ const session = object(entry, ['id', 'title', 'status', 'settings', 'projectLabel', 'modelLabel'], 'loaded session');
63
+ const id = workSessionId(session.id, 'session identifier');
64
+ if (ids.has(id))
65
+ throw new Error('Duplicate loaded session');
66
+ ids.add(id);
67
+ if (session.status !== 'idle' && session.status !== 'running')
68
+ throw new Error('Invalid session status');
69
+ return {
70
+ id, title: label(session.title, 'session title'), status: session.status,
71
+ settings: parseWorkSessionSettings(session.settings),
72
+ ...(session.projectLabel !== undefined ? { projectLabel: label(session.projectLabel, 'project label') } : {}),
73
+ ...(session.modelLabel !== undefined ? { modelLabel: label(session.modelLabel, 'model label') } : {}),
74
+ };
75
+ }),
76
+ };
77
+ for (const key of ['models', 'reasoningEfforts', 'permissionModes', 'executionModes']) {
78
+ if (input[key] !== undefined)
79
+ result[key] = choices(input[key], key === 'models');
80
+ }
81
+ if (input.defaults !== undefined)
82
+ result.defaults = parseWorkSessionSettings(input.defaults);
83
+ if (result.canCreate && !result.projects.length)
84
+ throw new Error('Creating sessions requires an advertised project');
85
+ if (JSON.stringify(result).length > 65_536)
86
+ throw new Error('Work session catalog is too large');
87
+ return result;
88
+ }
89
+ export function parseWorkSessionSelection(value) {
90
+ const mode = value?.mode;
91
+ if (mode === 'attach') {
92
+ const input = object(value, ['mode', 'sessionId'], 'attach selection');
93
+ return { mode, sessionId: workSessionId(input.sessionId, 'session identifier') };
94
+ }
95
+ if (mode === 'create') {
96
+ const { mode: _mode, ...settings } = object(value, ['mode', ...SETTINGS_KEYS], 'create selection');
97
+ return { mode, ...parseWorkSessionSettings(settings), projectId: workSessionId(settings.projectId, 'project identifier') };
98
+ }
99
+ throw new Error('Invalid work session selection');
100
+ }
101
+ export function assertWorkSessionSelectionAvailable(selection, catalog) {
102
+ if (selection.mode === 'attach') {
103
+ if (!catalog.canAttach || !catalog.sessions.some((session) => session.id === selection.sessionId))
104
+ throw new Error('Selected loaded session is unavailable');
105
+ return;
106
+ }
107
+ if (!catalog.canCreate || !catalog.projects.some((project) => project.id === selection.projectId))
108
+ throw new Error('Selected project is unavailable');
109
+ const modelId = selection.modelId ?? catalog.defaults?.modelId;
110
+ const model = catalog.models?.find((choice) => choice.id === modelId);
111
+ const available = {
112
+ modelId: catalog.models, reasoningEffort: model?.reasoningEfforts ?? catalog.reasoningEfforts,
113
+ permissionMode: catalog.permissionModes, executionMode: catalog.executionModes,
114
+ };
115
+ for (const key of ['modelId', 'reasoningEffort', 'permissionMode', 'executionMode']) {
116
+ if (selection[key] !== undefined && !available[key]?.some((choice) => choice.id === selection[key]))
117
+ throw new Error(`Selected ${key} is unavailable`);
118
+ }
119
+ }
120
+ export function parseWorkSessionRuntimeRegistration(value) {
121
+ const input = object(value, ['hostId', 'runtimeEpoch', 'displayName', 'catalog'], 'runtime registration');
122
+ return { hostId: workSessionId(input.hostId), runtimeEpoch: workSessionId(input.runtimeEpoch), displayName: label(input.displayName, 'host name'), catalog: parseWorkSessionCatalog(input.catalog) };
123
+ }
124
+ export function parseWorkSessionRuntimeAuth(value, extraKeys = []) {
125
+ const input = object(value, ['hostId', 'runtimeEpoch', 'leaseToken', ...extraKeys], 'runtime request');
126
+ return { hostId: workSessionId(input.hostId), runtimeEpoch: workSessionId(input.runtimeEpoch), leaseToken: workSessionId(input.leaseToken, 'lease token') };
127
+ }
128
+ export function parseRequestWorkSessionInput(value) {
129
+ const input = object(value, ['agentId', 'conversationId', 'requestId', 'hostId', 'runtimeEpoch', 'catalogRevision', 'selection'], 'work session request');
130
+ if (typeof input.requestId !== 'string' || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(input.requestId))
131
+ throw new Error('requestId must be a UUID');
132
+ return {
133
+ agentId: workSessionId(input.agentId), conversationId: workSessionId(input.conversationId), requestId: input.requestId,
134
+ hostId: workSessionId(input.hostId), runtimeEpoch: workSessionId(input.runtimeEpoch), catalogRevision: workSessionId(input.catalogRevision),
135
+ selection: parseWorkSessionSelection(input.selection),
136
+ };
137
+ }
138
+ export function parseWorkSessionCompletion(value) {
139
+ const status = value?.status;
140
+ if (status === 'attached') {
141
+ const input = object(value, ['status', 'nativeSessionId', 'settings'], 'attached result');
142
+ return { status, nativeSessionId: workSessionId(input.nativeSessionId), settings: parseWorkSessionSettings(input.settings) };
143
+ }
144
+ if (status === 'failed' || status === 'uncertain') {
145
+ const input = object(value, ['status', 'error'], 'failure result');
146
+ const error = object(input.error, ['code', 'message'], 'failure');
147
+ return { status, error: { code: workSessionId(error.code), message: label(error.message, 'failure message', 512) } };
148
+ }
149
+ throw new Error('Invalid work session result');
150
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@canonmsg/backend-contracts",
3
- "version": "8.2.0",
3
+ "version": "8.4.0",
4
4
  "description": "Canon backend contract helpers shared by Functions and stream-service",
5
5
  "type": "module",
6
6
  "main": "dist/cjs/index.js",
@@ -33,21 +33,19 @@
33
33
  "contracts",
34
34
  "wire"
35
35
  ],
36
- "repository": {
37
- "type": "git",
38
- "url": "https://github.com/HeyBobChan/canon",
39
- "directory": "packages/backend-contracts"
40
- },
41
- "homepage": "https://github.com/HeyBobChan/canon/tree/main/packages/backend-contracts",
36
+ "homepage": "https://canonmail.com/agents/contracts",
42
37
  "publishConfig": {
43
38
  "access": "public"
44
39
  },
45
40
  "devDependencies": {
46
- "@canonmsg/rich-cards": "^0.10.3",
41
+ "@canonmsg/rich-cards": "^0.10.5",
47
42
  "@types/node": "^22.0.0",
48
43
  "ajv": "^8.20.0",
49
44
  "typescript": "~5.7.0",
50
45
  "vitest": "^4.1.8"
51
46
  },
52
- "license": "MIT"
47
+ "license": "MIT",
48
+ "bugs": {
49
+ "url": "https://canonmail.com/support"
50
+ }
53
51
  }