@canonmsg/core 0.12.0 → 0.13.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.
@@ -2,20 +2,49 @@
2
2
  * Shared agent profile management — loading, locking, and resolution.
3
3
  * Used by both host.ts and server.ts.
4
4
  */
5
+ import type { AgentClientType } from './types.js';
5
6
  export interface AgentProfile {
6
7
  apiKey: string;
7
8
  agentId: string;
8
9
  agentName: string;
9
10
  registeredAt: string;
11
+ clientType?: AgentClientType;
12
+ baseUrl?: string;
13
+ streamUrl?: string;
14
+ rtdbUrl?: string;
15
+ runtimeId?: string;
16
+ }
17
+ export interface ProfileLockHandle {
18
+ profile: string;
19
+ pid: number;
20
+ token: string;
21
+ release(): void;
10
22
  }
11
23
  export declare const CANON_DIR: string;
12
24
  export declare const AGENTS_PATH: string;
13
25
  export declare const LOCKS_DIR: string;
26
+ export declare const PENDING_REGISTRATIONS_PATH: string;
14
27
  export declare function loadProfiles(): Record<string, AgentProfile>;
28
+ export declare function saveProfiles(profiles: Record<string, AgentProfile>): void;
29
+ export declare function upsertAgentProfile(name: string, profile: AgentProfile): Record<string, AgentProfile>;
15
30
  export declare function isProcessAlive(pid: number): boolean;
16
31
  export declare function isProfileLocked(profile: string): {
17
32
  locked: boolean;
18
33
  pid?: number;
19
34
  };
20
- export declare function acquireLock(profile: string): void;
21
- export declare function releaseLock(profile: string): void;
35
+ export declare function acquireLock(profile: string): ProfileLockHandle;
36
+ export declare function releaseLock(profile: string, token?: string): void;
37
+ export interface PendingRegistration {
38
+ profile: string;
39
+ clientType?: AgentClientType;
40
+ localRegistrationId: string;
41
+ requestId?: string;
42
+ pollToken?: string;
43
+ createdAt: string;
44
+ updatedAt: string;
45
+ }
46
+ export declare function loadPendingRegistrations(): Record<string, PendingRegistration>;
47
+ export declare function savePendingRegistrations(pending: Record<string, PendingRegistration>): void;
48
+ export declare function getOrCreatePendingRegistration(profile: string, clientType?: AgentClientType): PendingRegistration;
49
+ export declare function updatePendingRegistration(profile: string, patch: Partial<Pick<PendingRegistration, 'requestId' | 'pollToken' | 'clientType'>>): PendingRegistration;
50
+ export declare function clearPendingRegistration(profile: string): void;
@@ -2,13 +2,18 @@
2
2
  * Shared agent profile management — loading, locking, and resolution.
3
3
  * Used by both host.ts and server.ts.
4
4
  */
5
- import { readFileSync, writeFileSync, unlinkSync, mkdirSync } from 'node:fs';
6
- import { join } from 'node:path';
5
+ import { readFileSync, renameSync, writeFileSync, unlinkSync, mkdirSync } from 'node:fs';
6
+ import { closeSync, openSync } from 'node:fs';
7
+ import { randomUUID } from 'node:crypto';
8
+ import { join, resolve } from 'node:path';
7
9
  import { homedir } from 'node:os';
8
10
  // ── Paths ────────────────────────────────────────────────────────────
9
- export const CANON_DIR = join(homedir(), '.canon');
11
+ export const CANON_DIR = process.env.CANON_HOME
12
+ ? resolve(process.env.CANON_HOME)
13
+ : join(homedir(), '.canon');
10
14
  export const AGENTS_PATH = join(CANON_DIR, 'agents.json');
11
15
  export const LOCKS_DIR = join(CANON_DIR, 'locks');
16
+ export const PENDING_REGISTRATIONS_PATH = join(CANON_DIR, 'pending-registrations.json');
12
17
  // ── Profile loading ──────────────────────────────────────────────────
13
18
  export function loadProfiles() {
14
19
  try {
@@ -18,6 +23,24 @@ export function loadProfiles() {
18
23
  return {};
19
24
  }
20
25
  }
26
+ function writeJsonFile(path, value, mode = 0o600) {
27
+ mkdirSync(CANON_DIR, { recursive: true });
28
+ const tmpPath = `${path}.${process.pid}.${Date.now()}.tmp`;
29
+ writeFileSync(tmpPath, JSON.stringify(value, null, 2), { mode });
30
+ renameSync(tmpPath, path);
31
+ }
32
+ export function saveProfiles(profiles) {
33
+ writeJsonFile(AGENTS_PATH, profiles, 0o600);
34
+ }
35
+ export function upsertAgentProfile(name, profile) {
36
+ const profileName = name.trim();
37
+ if (!profileName)
38
+ throw new Error('Profile name is required');
39
+ const profiles = loadProfiles();
40
+ profiles[profileName] = profile;
41
+ saveProfiles(profiles);
42
+ return profiles;
43
+ }
21
44
  // ── Process locking ──────────────────────────────────────────────────
22
45
  export function isProcessAlive(pid) {
23
46
  try {
@@ -31,8 +54,9 @@ export function isProcessAlive(pid) {
31
54
  export function isProfileLocked(profile) {
32
55
  const lockPath = join(LOCKS_DIR, `${profile}.lock`);
33
56
  try {
34
- const pid = parseInt(readFileSync(lockPath, 'utf-8').trim());
35
- if (isProcessAlive(pid))
57
+ const lock = parseLock(readFileSync(lockPath, 'utf-8'));
58
+ const pid = lock?.pid;
59
+ if (pid && isProcessAlive(pid))
36
60
  return { locked: true, pid };
37
61
  // Stale lock — clean it up
38
62
  try {
@@ -45,19 +69,130 @@ export function isProfileLocked(profile) {
45
69
  }
46
70
  return { locked: false };
47
71
  }
72
+ function parseLock(raw) {
73
+ const trimmed = raw.trim();
74
+ if (!trimmed)
75
+ return null;
76
+ const legacyPid = Number.parseInt(trimmed, 10);
77
+ if (Number.isFinite(legacyPid) && String(legacyPid) === trimmed) {
78
+ return { pid: legacyPid };
79
+ }
80
+ try {
81
+ const data = JSON.parse(trimmed);
82
+ return typeof data.pid === 'number'
83
+ ? { pid: data.pid, token: typeof data.token === 'string' ? data.token : undefined }
84
+ : null;
85
+ }
86
+ catch {
87
+ return null;
88
+ }
89
+ }
48
90
  export function acquireLock(profile) {
49
91
  mkdirSync(LOCKS_DIR, { recursive: true });
50
92
  const lockPath = join(LOCKS_DIR, `${profile}.lock`);
51
- const check = isProfileLocked(profile);
52
- if (check.locked) {
53
- throw new Error(`Agent "${profile}" is in use by another session (PID ${check.pid})`);
93
+ const token = randomUUID();
94
+ const payload = JSON.stringify({
95
+ pid: process.pid,
96
+ token,
97
+ acquiredAt: new Date().toISOString(),
98
+ });
99
+ for (let attempt = 0; attempt < 2; attempt += 1) {
100
+ try {
101
+ const fd = openSync(lockPath, 'wx', 0o600);
102
+ try {
103
+ writeFileSync(fd, payload);
104
+ }
105
+ finally {
106
+ closeSync(fd);
107
+ }
108
+ return {
109
+ profile,
110
+ pid: process.pid,
111
+ token,
112
+ release: () => releaseLock(profile, token),
113
+ };
114
+ }
115
+ catch (error) {
116
+ if (error?.code !== 'EEXIST')
117
+ throw error;
118
+ const check = isProfileLocked(profile);
119
+ if (check.locked) {
120
+ throw new Error(`Agent "${profile}" is in use by another session (PID ${check.pid})`);
121
+ }
122
+ }
54
123
  }
55
- writeFileSync(lockPath, String(process.pid));
124
+ throw new Error(`Agent "${profile}" lock could not be acquired`);
56
125
  }
57
- export function releaseLock(profile) {
126
+ export function releaseLock(profile, token) {
58
127
  const lockPath = join(LOCKS_DIR, `${profile}.lock`);
128
+ if (token) {
129
+ try {
130
+ const lock = parseLock(readFileSync(lockPath, 'utf-8'));
131
+ if (lock?.token && lock.token !== token)
132
+ return;
133
+ }
134
+ catch {
135
+ return;
136
+ }
137
+ }
59
138
  try {
60
139
  unlinkSync(lockPath);
61
140
  }
62
141
  catch { }
63
142
  }
143
+ export function loadPendingRegistrations() {
144
+ try {
145
+ return JSON.parse(readFileSync(PENDING_REGISTRATIONS_PATH, 'utf-8'));
146
+ }
147
+ catch {
148
+ return {};
149
+ }
150
+ }
151
+ export function savePendingRegistrations(pending) {
152
+ writeJsonFile(PENDING_REGISTRATIONS_PATH, pending, 0o600);
153
+ }
154
+ export function getOrCreatePendingRegistration(profile, clientType) {
155
+ const now = new Date().toISOString();
156
+ const pending = loadPendingRegistrations();
157
+ const existing = pending[profile];
158
+ if (existing) {
159
+ const next = { ...existing, clientType, updatedAt: now };
160
+ pending[profile] = next;
161
+ savePendingRegistrations(pending);
162
+ return next;
163
+ }
164
+ const created = {
165
+ profile,
166
+ clientType,
167
+ localRegistrationId: randomUUID(),
168
+ createdAt: now,
169
+ updatedAt: now,
170
+ };
171
+ pending[profile] = created;
172
+ savePendingRegistrations(pending);
173
+ return created;
174
+ }
175
+ export function updatePendingRegistration(profile, patch) {
176
+ const pending = loadPendingRegistrations();
177
+ const existing = pending[profile] ?? {
178
+ profile,
179
+ localRegistrationId: randomUUID(),
180
+ createdAt: new Date().toISOString(),
181
+ updatedAt: new Date().toISOString(),
182
+ };
183
+ const next = {
184
+ ...existing,
185
+ ...patch,
186
+ updatedAt: new Date().toISOString(),
187
+ };
188
+ pending[profile] = next;
189
+ savePendingRegistrations(pending);
190
+ return next;
191
+ }
192
+ export function clearPendingRegistration(profile) {
193
+ const pending = loadPendingRegistrations();
194
+ if (pending[profile]) {
195
+ delete pending[profile];
196
+ savePendingRegistrations(pending);
197
+ }
198
+ }
@@ -10,16 +10,26 @@
10
10
  * 2. CANON_AGENT env var (named profile with lock)
11
11
  * 3. Auto-select from profiles (first unlocked, with lock)
12
12
  */
13
+ import { type ProfileLockHandle } from './agent-profiles.js';
14
+ import type { AgentClientType } from './types.js';
13
15
  export interface ResolvedAgent {
14
16
  apiKey: string;
15
17
  agentId?: string;
16
18
  profile: string | null;
19
+ agentName?: string;
20
+ clientType?: AgentClientType;
21
+ baseUrl?: string;
22
+ streamUrl?: string;
23
+ rtdbUrl?: string;
24
+ lockHandle?: ProfileLockHandle;
17
25
  }
18
26
  /** Get the currently locked profile name (for cleanup on shutdown). */
19
27
  export declare function getActiveProfile(): string | null;
28
+ export declare function getActiveProfileLock(): ProfileLockHandle | null;
20
29
  export declare function resolveCanonProfile(name: string, opts?: {
21
30
  logPrefix?: string;
22
31
  lock?: boolean;
32
+ expectedClientType?: AgentClientType;
23
33
  }): ResolvedAgent;
24
34
  /**
25
35
  * Resolve Canon agent credentials.
@@ -30,4 +40,6 @@ export declare function resolveCanonProfile(name: string, opts?: {
30
40
  */
31
41
  export declare function resolveCanonAgent(opts?: {
32
42
  logPrefix?: string;
43
+ expectedClientType?: AgentClientType;
44
+ lock?: boolean;
33
45
  }): ResolvedAgent;
@@ -12,10 +12,17 @@
12
12
  */
13
13
  import { loadProfiles, isProfileLocked, acquireLock, } from './agent-profiles.js';
14
14
  let activeResolvedProfile = null;
15
+ let activeLockHandle = null;
15
16
  /** Get the currently locked profile name (for cleanup on shutdown). */
16
17
  export function getActiveProfile() {
17
18
  return activeResolvedProfile;
18
19
  }
20
+ export function getActiveProfileLock() {
21
+ return activeLockHandle;
22
+ }
23
+ function profileMatches(profile, expectedClientType) {
24
+ return !expectedClientType || !profile.clientType || profile.clientType === expectedClientType;
25
+ }
19
26
  export function resolveCanonProfile(name, opts) {
20
27
  const prefix = opts?.logPrefix ?? '[canon]';
21
28
  const profileName = name.trim();
@@ -27,13 +34,25 @@ export function resolveCanonProfile(name, opts) {
27
34
  if (!profile) {
28
35
  throw new Error(`${prefix} Profile "${profileName}" not found in ~/.canon/agents.json`);
29
36
  }
37
+ if (!profileMatches(profile, opts?.expectedClientType)) {
38
+ throw new Error(`${prefix} Profile "${profileName}" is registered for ${profile.clientType}, not ${opts?.expectedClientType}`);
39
+ }
40
+ let lockHandle;
30
41
  if (opts?.lock) {
31
- acquireLock(profileName);
42
+ lockHandle = acquireLock(profileName);
43
+ activeResolvedProfile = profileName;
44
+ activeLockHandle = lockHandle;
32
45
  }
33
46
  return {
34
47
  apiKey: profile.apiKey,
35
48
  agentId: profile.agentId,
49
+ agentName: profile.agentName,
50
+ clientType: profile.clientType,
51
+ baseUrl: profile.baseUrl,
52
+ streamUrl: profile.streamUrl,
53
+ rtdbUrl: profile.rtdbUrl,
36
54
  profile: profileName,
55
+ lockHandle,
37
56
  };
38
57
  }
39
58
  /**
@@ -45,6 +64,7 @@ export function resolveCanonProfile(name, opts) {
45
64
  */
46
65
  export function resolveCanonAgent(opts) {
47
66
  const prefix = opts?.logPrefix ?? '[canon]';
67
+ const shouldLock = opts?.lock ?? true;
48
68
  // 1. Explicit API key (highest priority, no lock)
49
69
  // CANON_API_KEY is set by the host wrapper or user environment.
50
70
  // CANON_PLUGIN_API_KEY is set by plugin.json from user_config.
@@ -58,34 +78,30 @@ export function resolveCanonAgent(opts) {
58
78
  if (process.env.CANON_AGENT) {
59
79
  const resolved = resolveCanonProfile(process.env.CANON_AGENT, {
60
80
  logPrefix: prefix,
61
- lock: true,
81
+ lock: shouldLock,
82
+ expectedClientType: opts?.expectedClientType,
62
83
  });
63
- activeResolvedProfile = resolved.profile;
64
84
  return resolved;
65
85
  }
66
86
  // 3. Auto-select from profiles
67
87
  if (names.length === 0) {
68
- throw new Error(`${prefix} No agents registered. Run canon-register first.`);
88
+ throw new Error(`${prefix} No agents registered. Run a runtime register command first.`);
89
+ }
90
+ const viableNames = names.filter((name) => profileMatches(profiles[name], opts?.expectedClientType));
91
+ if (viableNames.length === 0) {
92
+ throw new Error(`${prefix} No ${opts?.expectedClientType ?? 'matching'} profiles found in ~/.canon/agents.json.`);
69
93
  }
70
- if (names.length === 1) {
71
- const resolved = resolveCanonProfile(names[0], {
94
+ if (viableNames.length === 1) {
95
+ const resolved = resolveCanonProfile(viableNames[0], {
72
96
  logPrefix: prefix,
73
- lock: true,
97
+ lock: shouldLock,
98
+ expectedClientType: opts?.expectedClientType,
74
99
  });
75
- activeResolvedProfile = resolved.profile;
76
100
  return resolved;
77
101
  }
78
- // Multiple agents pick first unlocked
79
- for (const name of names) {
80
- if (!isProfileLocked(name).locked) {
81
- const resolved = resolveCanonProfile(name, {
82
- logPrefix: prefix,
83
- lock: true,
84
- });
85
- activeResolvedProfile = resolved.profile;
86
- console.error(`${prefix} Auto-selected agent "${name}" (${profiles[name].agentName})`);
87
- return resolved;
88
- }
102
+ const unlocked = viableNames.filter((name) => !isProfileLocked(name).locked);
103
+ if (unlocked.length === 0) {
104
+ throw new Error(`${prefix} All matching agents are in use by other sessions. Run canon-necromance list to inspect them.`);
89
105
  }
90
- throw new Error(`${prefix} All agents are in use by other sessions.`);
106
+ throw new Error(`${prefix} Multiple profiles are available (${unlocked.join(', ')}). Set CANON_AGENT=<profile> or use canon-necromance revive <profile>.`);
91
107
  }
package/dist/client.d.ts CHANGED
@@ -16,6 +16,9 @@ export declare class CanonClient {
16
16
  agentId: string;
17
17
  }>;
18
18
  getAgentMe(): Promise<AgentContext>;
19
+ rotateAgentKey(): Promise<{
20
+ apiKey: string;
21
+ }>;
19
22
  getConversations(): Promise<CanonConversation[]>;
20
23
  getMessages(conversationId: string, limit?: number, before?: string): Promise<CanonMessage[]>;
21
24
  getMessagesPage(conversationId: string, limit?: number, before?: string): Promise<CanonMessagesPage>;
@@ -61,10 +64,13 @@ export declare class CanonClient {
61
64
  avatarUrl?: string;
62
65
  clientType?: string;
63
66
  requestedAgentId?: string;
67
+ localRegistrationId?: string;
64
68
  }): Promise<{
65
69
  requestId: string;
70
+ pollToken?: string;
66
71
  }>;
67
- static checkStatus(baseUrl: string | undefined, requestId: string): Promise<RegistrationStatus>;
72
+ static checkStatus(baseUrl: string | undefined, requestId: string, pollToken?: string): Promise<RegistrationStatus>;
73
+ static ackRegistrationStatus(baseUrl: string | undefined, requestId: string, pollToken?: string): Promise<void>;
68
74
  }
69
75
  export declare class CanonApiError extends Error {
70
76
  status: number;
package/dist/client.js CHANGED
@@ -34,6 +34,15 @@ export class CanonClient {
34
34
  throw new CanonApiError(res.status, await res.text());
35
35
  return res.json();
36
36
  }
37
+ async rotateAgentKey() {
38
+ const res = await fetch(`${this.baseUrl}/agents/keys/rotate`, {
39
+ method: 'POST',
40
+ headers: this.authHeaders(),
41
+ });
42
+ if (!res.ok)
43
+ throw new CanonApiError(res.status, await res.text());
44
+ return res.json();
45
+ }
37
46
  async getConversations() {
38
47
  const res = await fetch(`${this.baseUrl}/conversations`, {
39
48
  headers: this.authHeaders(),
@@ -360,13 +369,27 @@ export class CanonClient {
360
369
  throw new CanonApiError(res.status, await res.text());
361
370
  return res.json();
362
371
  }
363
- static async checkStatus(baseUrl, requestId) {
372
+ static async checkStatus(baseUrl, requestId, pollToken) {
364
373
  const url = baseUrl || DEFAULT_BASE_URL;
365
- const res = await fetch(`${url}/agents/status/${requestId}`);
374
+ const res = await fetch(`${url}/agents/status/${requestId}`, {
375
+ headers: pollToken ? { 'x-canon-poll-token': pollToken } : undefined,
376
+ });
366
377
  if (!res.ok)
367
378
  throw new CanonApiError(res.status, await res.text());
368
379
  return res.json();
369
380
  }
381
+ static async ackRegistrationStatus(baseUrl, requestId, pollToken) {
382
+ const url = baseUrl || DEFAULT_BASE_URL;
383
+ const res = await fetch(`${url}/agents/status/${requestId}/ack`, {
384
+ method: 'POST',
385
+ headers: {
386
+ 'Content-Type': 'application/json',
387
+ ...(pollToken ? { 'x-canon-poll-token': pollToken } : {}),
388
+ },
389
+ });
390
+ if (!res.ok)
391
+ throw new CanonApiError(res.status, await res.text());
392
+ }
370
393
  }
371
394
  export class CanonApiError extends Error {
372
395
  status;
package/dist/index.d.ts CHANGED
@@ -12,7 +12,7 @@ export type { PolicyRole, ParticipationStyle, RepresentationMode, PermissionLeve
12
12
  export { buildParticipationHistorySnapshot, buildParticipationHistorySnapshots, buildBehaviorPolicyLines, DEFAULT_PARTICIPATION_HISTORY_FETCH_LIMIT, evaluateParticipationPolicy, getDefaultParticipationPolicy, resolveAgentBehaviorPolicy, } from './policy.js';
13
13
  export { DEFAULT_RUNTIME_CAPABILITIES, HOST_ADMISSION_ACTION_CAPABILITIES, HOST_ADMISSION_ACTIONS_DISABLED, FINAL_MESSAGE_HANDOFF_MS, isTurnOpen, normalizeTurnMetadata, normalizeTurnState, resolveTurnMessageSemantics, shouldPromoteConversationMessage, shouldTriggerAgentTurn, } from './turn-protocol.js';
14
14
  export type { DeliveryIntent, TurnMessageSemantics, InboundDisposition, TurnLifecycleState, RuntimeCapabilities, HostAdmissionActionCapabilities, TurnState, TurnMetadata, TriggerDecision, } from './turn-protocol.js';
15
- export { registerAndWaitForApproval } from './registration.js';
15
+ export { ackRegistrationApproval, registerAndWaitForApproval, submitRegistrationRequest, waitForRegistrationApproval, } from './registration.js';
16
16
  export { ApprovalManager } from './approval-manager.js';
17
17
  export { generateApprovalId, buildApprovalRequest, buildApprovalReply, buildApprovalOutcome, parseTextApprovalReply, redactSecrets, } from './approval-format.js';
18
18
  export { DEFAULT_APPROVAL_CONFIG, } from './approval-types.js';
@@ -21,10 +21,12 @@ export { buildPlanApprovalReply, buildPlanApprovalRequest, buildQuestionReply, b
21
21
  export type { ClaudeQuestionMetadata, ClaudeQuestionReplyMetadata, PlanApprovalMetadata, PlanApprovalReplyMetadata, RuntimeQuestionDefinition, RuntimeQuestionOption, } from './runtime-cards.js';
22
22
  export { createStreamingHelper } from './streaming.js';
23
23
  export type { RTDBHandle, RTDBRef, ServerTimestamp, StreamingHelperOptions, StreamingNode } from './streaming.js';
24
- export { loadProfiles, isProfileLocked, acquireLock, releaseLock, isProcessAlive, CANON_DIR, AGENTS_PATH, LOCKS_DIR, } from './agent-profiles.js';
25
- export type { AgentProfile } from './agent-profiles.js';
26
- export { resolveCanonAgent, resolveCanonProfile, getActiveProfile } from './agent-resolver.js';
24
+ export { clearPendingRegistration, getOrCreatePendingRegistration, loadPendingRegistrations, loadProfiles, savePendingRegistrations, saveProfiles, updatePendingRegistration, upsertAgentProfile, isProfileLocked, acquireLock, releaseLock, isProcessAlive, CANON_DIR, AGENTS_PATH, LOCKS_DIR, } from './agent-profiles.js';
25
+ export type { AgentProfile, PendingRegistration, ProfileLockHandle } from './agent-profiles.js';
26
+ export { resolveCanonAgent, resolveCanonProfile, getActiveProfile, getActiveProfileLock } from './agent-resolver.js';
27
27
  export type { ResolvedAgent } from './agent-resolver.js';
28
+ export { RUNTIMES_DIR, buildLocalRuntimeId, clearRuntimeSessionState, describeProfileLock, heartbeatLocalRuntimeEntry, listLocalRuntimeEntries, loadRuntimeSessionState, markLocalRuntimeStopped, readLocalRuntimeEntry, removeLocalRuntimeEntry, saveRuntimeSessionState, upsertLocalRuntimeEntry, } from './local-runtime-catalog.js';
29
+ export type { LocalRuntimeCatalogEntry, LocalRuntimeKind, LocalRuntimeReviveCapability, LocalRuntimeSessionState, LocalRuntimeStatus, } from './local-runtime-catalog.js';
28
30
  export { buildConfiguredWorkspaceOptions, buildConversationEnvironmentKey, buildConversationWorktreeSpec, buildPublicWorkspaceOptions, buildWorkspaceOptionId, EXECUTION_ENVIRONMENT_MODES, isEnabledFlag, isExecutionEnvironmentMode, normalizeOptionalString, readSessionWorkspaceConfig, resolveConfiguredWorkspaceCwd, ExecutionEnvironmentError, prepareConversationEnvironment, releaseConversationEnvironment, } from './execution-environment.js';
29
31
  export type { ConfiguredWorkspaceOption, ExecutionEnvironmentMode, PreparedExecutionEnvironment, SessionWorkspaceConfig, } from './execution-environment.js';
30
32
  export { initRTDBAuth, rtdbWrite, rtdbRead, patchAgentSessionSnapshot, patchRuntimeInfo, writeRuntimeInfo, clearRuntimeInfo, writeSessionState, clearSessionState, writeTurnState, clearTurnState, } from './rtdb-rest.js';
package/dist/index.js CHANGED
@@ -11,7 +11,7 @@ export { buildParticipationHistorySnapshot, buildParticipationHistorySnapshots,
11
11
  // Turn protocol
12
12
  export { DEFAULT_RUNTIME_CAPABILITIES, HOST_ADMISSION_ACTION_CAPABILITIES, HOST_ADMISSION_ACTIONS_DISABLED, FINAL_MESSAGE_HANDOFF_MS, isTurnOpen, normalizeTurnMetadata, normalizeTurnState, resolveTurnMessageSemantics, shouldPromoteConversationMessage, shouldTriggerAgentTurn, } from './turn-protocol.js';
13
13
  // Registration
14
- export { registerAndWaitForApproval } from './registration.js';
14
+ export { ackRegistrationApproval, registerAndWaitForApproval, submitRegistrationRequest, waitForRegistrationApproval, } from './registration.js';
15
15
  // Approval
16
16
  export { ApprovalManager } from './approval-manager.js';
17
17
  export { generateApprovalId, buildApprovalRequest, buildApprovalReply, buildApprovalOutcome, parseTextApprovalReply, redactSecrets, } from './approval-format.js';
@@ -20,9 +20,11 @@ export { buildPlanApprovalReply, buildPlanApprovalRequest, buildQuestionReply, b
20
20
  // Streaming (RTDB helpers)
21
21
  export { createStreamingHelper } from './streaming.js';
22
22
  // Agent profiles (loading, locking, resolution)
23
- export { loadProfiles, isProfileLocked, acquireLock, releaseLock, isProcessAlive, CANON_DIR, AGENTS_PATH, LOCKS_DIR, } from './agent-profiles.js';
23
+ export { clearPendingRegistration, getOrCreatePendingRegistration, loadPendingRegistrations, loadProfiles, savePendingRegistrations, saveProfiles, updatePendingRegistration, upsertAgentProfile, isProfileLocked, acquireLock, releaseLock, isProcessAlive, CANON_DIR, AGENTS_PATH, LOCKS_DIR, } from './agent-profiles.js';
24
24
  // Agent resolver
25
- export { resolveCanonAgent, resolveCanonProfile, getActiveProfile } from './agent-resolver.js';
25
+ export { resolveCanonAgent, resolveCanonProfile, getActiveProfile, getActiveProfileLock } from './agent-resolver.js';
26
+ // Local runtime catalog
27
+ export { RUNTIMES_DIR, buildLocalRuntimeId, clearRuntimeSessionState, describeProfileLock, heartbeatLocalRuntimeEntry, listLocalRuntimeEntries, loadRuntimeSessionState, markLocalRuntimeStopped, readLocalRuntimeEntry, removeLocalRuntimeEntry, saveRuntimeSessionState, upsertLocalRuntimeEntry, } from './local-runtime-catalog.js';
26
28
  // Execution environments for host-mode coding sessions
27
29
  export { buildConfiguredWorkspaceOptions, buildConversationEnvironmentKey, buildConversationWorktreeSpec, buildPublicWorkspaceOptions, buildWorkspaceOptionId, EXECUTION_ENVIRONMENT_MODES, isEnabledFlag, isExecutionEnvironmentMode, normalizeOptionalString, readSessionWorkspaceConfig, resolveConfiguredWorkspaceCwd, ExecutionEnvironmentError, prepareConversationEnvironment, releaseConversationEnvironment, } from './execution-environment.js';
28
30
  // RTDB REST helpers (token exchange, session state, generic read/write)
@@ -0,0 +1,65 @@
1
+ import type { AgentClientType, ExecutionEnvironmentMode } from './types.js';
2
+ export type LocalRuntimeKind = AgentClientType | 'sdk';
3
+ export type LocalRuntimeStatus = 'running' | 'offline' | 'stale' | 'manual' | 'embedded';
4
+ export type LocalRuntimeReviveCapability = 'revivable' | 'manual' | 'embedded' | 'missing-profile';
5
+ export interface LocalRuntimeSessionState {
6
+ conversationId: string;
7
+ workspaceId?: string;
8
+ baseCwd: string;
9
+ executionMode?: ExecutionEnvironmentMode;
10
+ threadId?: string;
11
+ claudeSessionId?: string;
12
+ lastInboundMessageId?: string;
13
+ updatedAt: string;
14
+ }
15
+ export interface LocalRuntimeCatalogEntry {
16
+ id: string;
17
+ runtime: LocalRuntimeKind;
18
+ profile: string | null;
19
+ agentId?: string;
20
+ agentName?: string;
21
+ cwd: string;
22
+ baseCwd?: string;
23
+ workspaceRoots?: string[];
24
+ workspaces?: string[];
25
+ launchCommand: string[];
26
+ pid?: number;
27
+ status: LocalRuntimeStatus;
28
+ reviveCapability: LocalRuntimeReviveCapability;
29
+ surfaceMode?: 'host' | 'channel' | 'embedded';
30
+ lastStartedAt?: string;
31
+ lastHeartbeatAt?: string;
32
+ lastStoppedAt?: string;
33
+ lastAuthError?: string;
34
+ lastError?: string;
35
+ sessions?: Record<string, LocalRuntimeSessionState>;
36
+ }
37
+ export declare const RUNTIMES_DIR: string;
38
+ export declare function buildLocalRuntimeId(input: {
39
+ runtime: LocalRuntimeKind;
40
+ profile?: string | null;
41
+ cwd: string;
42
+ launchCommand?: string[];
43
+ }): string;
44
+ export declare function readLocalRuntimeEntry(id: string): LocalRuntimeCatalogEntry | null;
45
+ export declare function upsertLocalRuntimeEntry(entry: LocalRuntimeCatalogEntry): LocalRuntimeCatalogEntry;
46
+ export declare function heartbeatLocalRuntimeEntry(id: string, patch?: Partial<LocalRuntimeCatalogEntry>): LocalRuntimeCatalogEntry | null;
47
+ export declare function markLocalRuntimeStopped(id: string, patch?: Partial<LocalRuntimeCatalogEntry>): LocalRuntimeCatalogEntry | null;
48
+ export declare function removeLocalRuntimeEntry(id: string): void;
49
+ export declare function listLocalRuntimeEntries(options?: {
50
+ runtime?: LocalRuntimeKind;
51
+ }): LocalRuntimeCatalogEntry[];
52
+ export declare function loadRuntimeSessionState(runtimeId: string, input: {
53
+ conversationId: string;
54
+ baseCwd: string;
55
+ executionMode?: ExecutionEnvironmentMode;
56
+ workspaceId?: string;
57
+ }): LocalRuntimeSessionState | null;
58
+ export declare function saveRuntimeSessionState(runtimeId: string, input: Omit<LocalRuntimeSessionState, 'updatedAt'>): LocalRuntimeSessionState;
59
+ export declare function clearRuntimeSessionState(runtimeId: string, input: {
60
+ conversationId: string;
61
+ baseCwd?: string;
62
+ executionMode?: ExecutionEnvironmentMode;
63
+ workspaceId?: string;
64
+ }): void;
65
+ export declare function describeProfileLock(profile: string): string;
@@ -0,0 +1,200 @@
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, unlinkSync, writeFileSync, } from 'node:fs';
2
+ import { createHash } from 'node:crypto';
3
+ import { join, resolve } from 'node:path';
4
+ import { CANON_DIR, isProcessAlive, isProfileLocked, loadProfiles } from './agent-profiles.js';
5
+ export const RUNTIMES_DIR = join(CANON_DIR, 'runtimes');
6
+ const LEGACY_CODEX_SESSIONS_PATH = join(CANON_DIR, 'codex-sessions.json');
7
+ function shortHash(value) {
8
+ return createHash('sha256').update(value).digest('hex').slice(0, 16);
9
+ }
10
+ function safeRuntimeFileName(id) {
11
+ return `${shortHash(id)}.json`;
12
+ }
13
+ function runtimePath(id) {
14
+ return join(RUNTIMES_DIR, safeRuntimeFileName(id));
15
+ }
16
+ function writeJsonAtomic(path, value) {
17
+ mkdirSync(RUNTIMES_DIR, { recursive: true });
18
+ const tmp = `${path}.${process.pid}.${Date.now()}.tmp`;
19
+ writeFileSync(tmp, JSON.stringify(value, null, 2), { mode: 0o600 });
20
+ renameSync(tmp, path);
21
+ }
22
+ export function buildLocalRuntimeId(input) {
23
+ const profile = input.profile ?? 'manual';
24
+ return `${input.runtime}:${profile}:${shortHash(`${resolve(input.cwd)}:${(input.launchCommand ?? []).join('\0')}`)}`;
25
+ }
26
+ export function readLocalRuntimeEntry(id) {
27
+ try {
28
+ const parsed = JSON.parse(readFileSync(runtimePath(id), 'utf-8'));
29
+ return parsed.id === id ? parsed : null;
30
+ }
31
+ catch {
32
+ return null;
33
+ }
34
+ }
35
+ export function upsertLocalRuntimeEntry(entry) {
36
+ const existing = readLocalRuntimeEntry(entry.id);
37
+ const next = {
38
+ ...existing,
39
+ ...entry,
40
+ sessions: {
41
+ ...(existing?.sessions ?? {}),
42
+ ...(entry.sessions ?? {}),
43
+ },
44
+ };
45
+ writeJsonAtomic(runtimePath(entry.id), next);
46
+ return next;
47
+ }
48
+ export function heartbeatLocalRuntimeEntry(id, patch = {}) {
49
+ const existing = readLocalRuntimeEntry(id);
50
+ if (!existing)
51
+ return null;
52
+ return upsertLocalRuntimeEntry({
53
+ ...existing,
54
+ ...patch,
55
+ id,
56
+ status: 'running',
57
+ pid: patch.pid ?? process.pid,
58
+ lastHeartbeatAt: new Date().toISOString(),
59
+ });
60
+ }
61
+ export function markLocalRuntimeStopped(id, patch = {}) {
62
+ const existing = readLocalRuntimeEntry(id);
63
+ if (!existing)
64
+ return null;
65
+ return upsertLocalRuntimeEntry({
66
+ ...existing,
67
+ ...patch,
68
+ id,
69
+ status: existing.reviveCapability === 'embedded' ? 'embedded' : 'offline',
70
+ pid: undefined,
71
+ lastStoppedAt: new Date().toISOString(),
72
+ });
73
+ }
74
+ export function removeLocalRuntimeEntry(id) {
75
+ try {
76
+ unlinkSync(runtimePath(id));
77
+ }
78
+ catch { }
79
+ }
80
+ function deriveRuntimeState(entry) {
81
+ let status = entry.status;
82
+ if (status === 'running' && entry.pid && !isProcessAlive(entry.pid)) {
83
+ status = 'stale';
84
+ }
85
+ const profiles = loadProfiles();
86
+ let reviveCapability = entry.reviveCapability;
87
+ if (entry.profile && !profiles[entry.profile]) {
88
+ reviveCapability = 'missing-profile';
89
+ }
90
+ return { ...entry, status, reviveCapability };
91
+ }
92
+ export function listLocalRuntimeEntries(options = {}) {
93
+ if (!existsSync(RUNTIMES_DIR))
94
+ return [];
95
+ const entries = [];
96
+ for (const name of readdirSync(RUNTIMES_DIR)) {
97
+ if (!name.endsWith('.json'))
98
+ continue;
99
+ try {
100
+ const entry = JSON.parse(readFileSync(join(RUNTIMES_DIR, name), 'utf-8'));
101
+ if (options.runtime && entry.runtime !== options.runtime)
102
+ continue;
103
+ entries.push(deriveRuntimeState(entry));
104
+ }
105
+ catch {
106
+ // Ignore corrupt breadcrumbs; they should not block the manager.
107
+ }
108
+ }
109
+ return entries.sort((a, b) => {
110
+ const at = a.lastHeartbeatAt ?? a.lastStartedAt ?? a.lastStoppedAt ?? '';
111
+ const bt = b.lastHeartbeatAt ?? b.lastStartedAt ?? b.lastStoppedAt ?? '';
112
+ return bt.localeCompare(at);
113
+ });
114
+ }
115
+ function sessionKey(input) {
116
+ return shortHash([
117
+ input.conversationId,
118
+ resolve(input.baseCwd),
119
+ input.executionMode ?? 'unknown',
120
+ input.workspaceId ?? '',
121
+ ].join('\0'));
122
+ }
123
+ export function loadRuntimeSessionState(runtimeId, input) {
124
+ migrateLegacyCodexSessions(runtimeId);
125
+ const entry = readLocalRuntimeEntry(runtimeId);
126
+ return entry?.sessions?.[sessionKey(input)] ?? null;
127
+ }
128
+ export function saveRuntimeSessionState(runtimeId, input) {
129
+ const entry = readLocalRuntimeEntry(runtimeId);
130
+ if (!entry) {
131
+ throw new Error(`Runtime catalog entry not found: ${runtimeId}`);
132
+ }
133
+ const key = sessionKey(input);
134
+ const existingState = entry.sessions?.[key];
135
+ const nextState = {
136
+ ...existingState,
137
+ ...input,
138
+ updatedAt: new Date().toISOString(),
139
+ };
140
+ upsertLocalRuntimeEntry({
141
+ ...entry,
142
+ sessions: {
143
+ ...(entry.sessions ?? {}),
144
+ [key]: nextState,
145
+ },
146
+ });
147
+ return nextState;
148
+ }
149
+ export function clearRuntimeSessionState(runtimeId, input) {
150
+ const entry = readLocalRuntimeEntry(runtimeId);
151
+ if (!entry?.sessions)
152
+ return;
153
+ const sessions = { ...entry.sessions };
154
+ if (input.baseCwd) {
155
+ delete sessions[sessionKey({
156
+ conversationId: input.conversationId,
157
+ baseCwd: input.baseCwd,
158
+ executionMode: input.executionMode,
159
+ workspaceId: input.workspaceId,
160
+ })];
161
+ }
162
+ else {
163
+ for (const [key, state] of Object.entries(sessions)) {
164
+ if (state.conversationId === input.conversationId)
165
+ delete sessions[key];
166
+ }
167
+ }
168
+ upsertLocalRuntimeEntry({ ...entry, sessions });
169
+ }
170
+ function migrateLegacyCodexSessions(runtimeId) {
171
+ if (!existsSync(LEGACY_CODEX_SESSIONS_PATH))
172
+ return;
173
+ const entry = readLocalRuntimeEntry(runtimeId);
174
+ if (!entry || entry.runtime !== 'codex')
175
+ return;
176
+ try {
177
+ const legacy = JSON.parse(readFileSync(LEGACY_CODEX_SESSIONS_PATH, 'utf-8'));
178
+ const agentSessions = entry.agentId ? legacy.agents?.[entry.agentId] : null;
179
+ if (!agentSessions)
180
+ return;
181
+ const sessions = { ...(entry.sessions ?? {}) };
182
+ for (const [conversationId, state] of Object.entries(agentSessions)) {
183
+ const baseCwd = state.cwd;
184
+ sessions[sessionKey({ conversationId, baseCwd })] = {
185
+ conversationId,
186
+ baseCwd,
187
+ threadId: state.threadId,
188
+ updatedAt: state.updatedAt,
189
+ };
190
+ }
191
+ upsertLocalRuntimeEntry({ ...entry, sessions });
192
+ }
193
+ catch {
194
+ return;
195
+ }
196
+ }
197
+ export function describeProfileLock(profile) {
198
+ const lock = isProfileLocked(profile);
199
+ return lock.locked ? `locked by PID ${lock.pid}` : 'available';
200
+ }
@@ -8,6 +8,14 @@ import type { RegistrationInput, RegistrationResult, RegistrationStatus } from '
8
8
  * 3. On approval, returns the API key
9
9
  */
10
10
  export declare function registerAndWaitForApproval(input: RegistrationInput, callbacks?: {
11
- onSubmitted?: (requestId: string) => void;
11
+ onSubmitted?: (requestId: string, pollToken?: string) => void;
12
12
  onPollUpdate?: (status: RegistrationStatus) => void;
13
13
  }): Promise<RegistrationResult>;
14
+ export declare function submitRegistrationRequest(input: RegistrationInput): Promise<{
15
+ requestId: string;
16
+ pollToken?: string;
17
+ }>;
18
+ export declare function waitForRegistrationApproval(baseUrl: string | undefined, requestId: string, pollToken?: string, callbacks?: {
19
+ onPollUpdate?: (status: RegistrationStatus) => void;
20
+ }): Promise<RegistrationResult>;
21
+ export declare function ackRegistrationApproval(baseUrl: string | undefined, requestId: string, pollToken?: string): Promise<void>;
@@ -10,7 +10,12 @@ const POLL_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
10
10
  * 3. On approval, returns the API key
11
11
  */
12
12
  export async function registerAndWaitForApproval(input, callbacks) {
13
- const { requestId } = await CanonClient.register(input.baseUrl, {
13
+ const submitted = await submitRegistrationRequest(input);
14
+ callbacks?.onSubmitted?.(submitted.requestId, submitted.pollToken);
15
+ return waitForRegistrationApproval(input.baseUrl, submitted.requestId, submitted.pollToken, callbacks);
16
+ }
17
+ export async function submitRegistrationRequest(input) {
18
+ return CanonClient.register(input.baseUrl, {
14
19
  name: input.name,
15
20
  description: input.description,
16
21
  ownerPhone: input.ownerPhone,
@@ -18,29 +23,47 @@ export async function registerAndWaitForApproval(input, callbacks) {
18
23
  avatarUrl: input.avatarUrl,
19
24
  clientType: input.clientType,
20
25
  requestedAgentId: input.requestedAgentId,
26
+ localRegistrationId: input.localRegistrationId,
21
27
  });
22
- callbacks?.onSubmitted?.(requestId);
28
+ }
29
+ export async function waitForRegistrationApproval(baseUrl, requestId, pollToken, callbacks) {
23
30
  const deadline = Date.now() + POLL_TIMEOUT_MS;
24
31
  while (Date.now() < deadline) {
25
32
  await sleep(POLL_INTERVAL_MS);
26
- const result = await CanonClient.checkStatus(input.baseUrl, requestId);
33
+ const result = await CanonClient.checkStatus(baseUrl, requestId, pollToken);
27
34
  callbacks?.onPollUpdate?.(result);
28
35
  if (result.status === 'approved') {
36
+ if (!result.apiKey) {
37
+ return {
38
+ status: 'timeout',
39
+ requestId,
40
+ pollToken,
41
+ agentId: result.agentId,
42
+ agentName: result.agentName,
43
+ };
44
+ }
29
45
  return {
30
46
  status: 'approved',
31
47
  apiKey: result.apiKey,
32
48
  agentId: result.agentId,
33
49
  agentName: result.agentName,
50
+ requestId,
51
+ pollToken,
34
52
  };
35
53
  }
36
54
  if (result.status === 'rejected') {
37
55
  return {
38
56
  status: 'rejected',
39
57
  agentName: result.agentName,
58
+ requestId,
59
+ pollToken,
40
60
  };
41
61
  }
42
62
  }
43
- return { status: 'timeout' };
63
+ return { status: 'timeout', requestId, pollToken };
64
+ }
65
+ export async function ackRegistrationApproval(baseUrl, requestId, pollToken) {
66
+ await CanonClient.ackRegistrationStatus(baseUrl, requestId, pollToken);
44
67
  }
45
68
  function sleep(ms) {
46
69
  return new Promise((resolve) => setTimeout(resolve, ms));
package/dist/types.d.ts CHANGED
@@ -605,15 +605,18 @@ export interface RegistrationInput {
605
605
  baseUrl?: string;
606
606
  clientType?: AgentClientType;
607
607
  requestedAgentId?: string;
608
+ localRegistrationId?: string;
608
609
  }
609
610
  export interface RegistrationResult {
610
611
  status: 'approved' | 'rejected' | 'timeout';
611
612
  apiKey?: string;
612
613
  agentId?: string;
613
614
  agentName?: string;
615
+ requestId?: string;
616
+ pollToken?: string;
614
617
  }
615
618
  export interface RegistrationStatus {
616
- status: 'pending' | 'approved' | 'rejected';
619
+ status: 'pending' | 'approving' | 'approved' | 'rejected';
617
620
  agentName: string;
618
621
  agentId?: string;
619
622
  apiKey?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@canonmsg/core",
3
- "version": "0.12.0",
3
+ "version": "0.13.0",
4
4
  "description": "Canon core — shared types, REST client, SSE stream, and registration for Canon messaging",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",