instar 1.3.373 → 1.3.375

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.
@@ -7,6 +7,11 @@
7
7
  * When Telegram is configured, wires up message routing:
8
8
  * topic message → find/spawn session → inject message → session replies via [telegram:N]
9
9
  */
10
+ import { SessionManager } from '../core/SessionManager.js';
11
+ import { TelegramAdapter } from '../messaging/TelegramAdapter.js';
12
+ import { TopicMemory } from '../memory/TopicMemory.js';
13
+ import { QuotaTracker } from '../monitoring/QuotaTracker.js';
14
+ import { UserManager } from '../users/UserManager.js';
10
15
  interface StartOptions {
11
16
  foreground?: boolean;
12
17
  dir?: string;
@@ -14,6 +19,7 @@ interface StartOptions {
14
19
  * Commander maps --no-telegram to telegram: false. */
15
20
  telegram?: boolean;
16
21
  }
22
+ export declare function wireTelegramRouting(telegram: TelegramAdapter, sessionManager: SessionManager, quotaTracker?: QuotaTracker, topicMemory?: TopicMemory, userManager?: UserManager, fixCommandHandler?: (topicId: number, text: string) => Promise<boolean>, getHubDeps?: () => import('../threadline/hubCommands.js').HubBindDeps | null, getTopicOperatorStore?: () => import('../users/TopicOperatorStore.js').TopicOperatorStore | null): void;
17
23
  export declare function startServer(options: StartOptions): Promise<void>;
18
24
  export declare function stopServer(options: {
19
25
  dir?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/commands/server.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AA6SH,UAAU,YAAY;IACpB,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb;2DACuD;IACvD,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AAuxDD,wBAAsB,WAAW,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAwpTtE;AAED,wBAAsB,UAAU,CAAC,OAAO,EAAE;IAAE,GAAG,CAAC,EAAE,MAAM,CAAA;CAAE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OAAO,EAAE;IAAE,GAAG,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAsDzE;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,aAAa,CAAC,OAAO,EAAE;IAAE,GAAG,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAuD5E"}
@@ -304,6 +304,11 @@ function isAutostartInstalled(projectName) {
304
304
  let _orphanReaper = null;
305
305
  let _memoryMonitor = null;
306
306
  let _fixDeps = null;
307
+ // Late-bound ref to the running AgentServer: wireTelegramRouting's
308
+ // topic-operator getter (Know Your Principal increment 2e) resolves the
309
+ // server's store at message-time — the server is constructed long after
310
+ // routing is wired, and the store must be the server's OWN instance.
311
+ let _agentServerRef = null;
307
312
  // Module-level reference for session resume mapping.
308
313
  // Set once in startServer() and used by spawnSessionForTopic/respawnSessionForTopic.
309
314
  let _topicResumeMap = null;
@@ -1067,10 +1072,15 @@ function messageToPipeline(msg, topicName) {
1067
1072
  timestamp: msg.receivedAt,
1068
1073
  };
1069
1074
  }
1070
- function wireTelegramRouting(telegram, sessionManager, quotaTracker, topicMemory, userManager, fixCommandHandler,
1075
+ export function wireTelegramRouting(telegram, sessionManager, quotaTracker, topicMemory, userManager, fixCommandHandler,
1071
1076
  // Late-bound: the threadline hub deps are constructed AFTER this is wired, so
1072
1077
  // resolve them at message-time (CMT-529 deterministic "open this" intercept).
1073
- getHubDeps) {
1078
+ getHubDeps,
1079
+ // Late-bound (same reason as getHubDeps): the AgentServer's TopicOperatorStore —
1080
+ // the SAME instance the routes use (a second instance on the same file would
1081
+ // lose updates between the two in-memory caches). Know Your Principal #898,
1082
+ // increment 2e: the polling-path operator auto-bind.
1083
+ getTopicOperatorStore) {
1074
1084
  // Guard: tracks which topic IDs have a spawn in progress.
1075
1085
  // Prevents duplicate concurrent spawns for the same topic when messages
1076
1086
  // arrive faster than the async spawn completes.
@@ -1085,6 +1095,30 @@ getHubDeps) {
1085
1095
  const resolvedUser = telegramUserId && userManager
1086
1096
  ? userManager.resolveFromTelegramUserId(telegramUserId)
1087
1097
  : null;
1098
+ // Topic-operator auto-bind (Know Your Principal #898, increment 2e — the
1099
+ // POLLING-path writer; the lifeline-forward path already binds in routes.ts
1100
+ // #909). This onTopicMessage seam is the convergence BOTH ingress paths
1101
+ // reach, so binding here closes the no-lifeline gap; the routes-side bind
1102
+ // stays (idempotent — same store instance, identical record skips the
1103
+ // write). The isAuthorizedSender check is LOAD-BEARING: the lifeline path
1104
+ // fires this callback for unauthorized senders too (it only skips its own
1105
+ // bind), so without the check here an unauthorized group member could seat
1106
+ // themselves as operator — the cross-principal "Caroline" bug. Fail-soft:
1107
+ // no store / unauthorized / error → no-op and routing continues.
1108
+ try {
1109
+ const opStore = getTopicOperatorStore?.() ?? null;
1110
+ if (opStore && telegramUserId && telegram.isAuthorizedSender(telegramUserId)) {
1111
+ opStore.setOperator(topicId, {
1112
+ platform: 'telegram',
1113
+ uid: String(telegramUserId),
1114
+ displayName: msg.metadata?.firstName ?? undefined,
1115
+ });
1116
+ }
1117
+ }
1118
+ catch (err) {
1119
+ // @silent-fallback-ok — an auto-bind failure must never break message routing.
1120
+ console.error(`[telegram] topic-operator auto-bind error (non-fatal): ${err instanceof Error ? err.message : err}`);
1121
+ }
1088
1122
  // In lifeline-owned polling mode (deep-signal, echo) TelegramAdapter's
1089
1123
  // own poll loop never runs, so its handleCommand() never fires on forwarded
1090
1124
  // messages. Route slash-commands through it here so /route, /sessions, /claim,
@@ -3581,7 +3615,7 @@ export async function startServer(options) {
3581
3615
  // reached the AI session as plain chat text.
3582
3616
  const userManagerSendOnly = new UserManager(config.stateDir, config.users);
3583
3617
  _fixDeps = { state, liveConfig, sessionManager, telegram, config };
3584
- wireTelegramRouting(telegram, sessionManager, quotaTracker, topicMemory, userManagerSendOnly, (topicId, text) => handleFixCommand(topicId, text, _fixDeps), () => (collaborationSurfacer && conversationStore && telegram) ? { collaborationSurfacer, conversationStore, commitmentTracker, telegram, brief: briefDeps } : null);
3618
+ wireTelegramRouting(telegram, sessionManager, quotaTracker, topicMemory, userManagerSendOnly, (topicId, text) => handleFixCommand(topicId, text, _fixDeps), () => (collaborationSurfacer && conversationStore && telegram) ? { collaborationSurfacer, conversationStore, commitmentTracker, telegram, brief: briefDeps } : null, () => _agentServerRef?.getTopicOperatorStore() ?? null);
3585
3619
  wireTelegramCallbacks(telegram, sessionManager, state, quotaTracker, undefined, config.sessions.claudePath, topicMemory);
3586
3620
  console.log(pc.green(' Telegram routing + command callbacks wired (send-only)'));
3587
3621
  }
@@ -3763,7 +3797,7 @@ export async function startServer(options) {
3763
3797
  config,
3764
3798
  };
3765
3799
  // Wire up topic → session routing and session management callbacks
3766
- wireTelegramRouting(telegram, sessionManager, quotaTracker, topicMemory, userManager, (topicId, text) => handleFixCommand(topicId, text, _fixDeps), () => (collaborationSurfacer && conversationStore && telegram) ? { collaborationSurfacer, conversationStore, commitmentTracker, telegram, brief: briefDeps } : null);
3800
+ wireTelegramRouting(telegram, sessionManager, quotaTracker, topicMemory, userManager, (topicId, text) => handleFixCommand(topicId, text, _fixDeps), () => (collaborationSurfacer && conversationStore && telegram) ? { collaborationSurfacer, conversationStore, commitmentTracker, telegram, brief: briefDeps } : null, () => _agentServerRef?.getTopicOperatorStore() ?? null);
3767
3801
  wireTelegramCallbacks(telegram, sessionManager, state, quotaTracker, accountSwitcher, config.sessions.claudePath, topicMemory);
3768
3802
  // Wire up unknown-user handling (Multi-User Setup Wizard Phase 4.5)
3769
3803
  telegram.onGetRegistrationPolicy = () => ({
@@ -10897,6 +10931,10 @@ export async function startServer(options) {
10897
10931
  console.log(pc.dim(` [session-pool] rollout gate not wired: ${err instanceof Error ? err.message : String(err)}`));
10898
10932
  }
10899
10933
  const server = new AgentServer({ config, sessionManager, state, scheduler, telegram, relationships, feedback, feedbackAnomalyDetector, dispatches, updateChecker, autoUpdater, autoDispatcher, quotaTracker, quotaManager, publisher, viewer, tunnel, evolution, watchdog, topicMemory, triageNurse, projectMapper, coherenceGate: scopeVerifier, contextHierarchy, canonicalState, operationGate, sentinel, adaptiveTrust, memoryMonitor, orphanReaper, coherenceMonitor, commitmentTracker, semanticMemory, activitySentinel, rateLimitSentinel, releaseReadinessSentinel: releaseReadinessSentinel ?? undefined, messageRouter, summarySentinel, spawnManager, systemReviewer, capabilityMapper, selfKnowledgeTree, coverageAuditor, topicResumeMap: _topicResumeMap ?? undefined, sessionRefresh: _sessionRefresh ?? undefined, autonomyManager, trustElevationTracker, autonomousEvolution, coordinator: coordinator.enabled ? coordinator : undefined, localSigningKeyPem, leaseTransport, onLeasePullRequest: () => leaseCoordinatorRef?.currentLease() ?? null, liveTailReceiver, handoffWireTransport, onHandoffBegin, onHandoffInitiate: handoffInitiate, handoffInProgress: handoffSentinelInProgress, messageLedger, currentInboundByTopic, replyMarkerTransport, onReplyMarker: messageLedger ? (marker) => { const m = marker; messageLedger.applyRemoteReplyMarker(m.dedupeKey, { platform: m.platform, replyIdempotencyKey: m.replyIdempotencyKey, epoch: m.epoch, topic: m.topic ?? null }); } : undefined, whatsapp: whatsappAdapter, slack: slackAdapter, imessage: imessageAdapter, whatsappBusinessBackend, messageBridge, hookEventReceiver, worktreeMonitor, subagentTracker, instructionsVerifier, handshakeManager: threadlineHandshake, threadlineRouter, conversationStore, warrantsReplyGate, collaborationSurfacer, threadResumeMap, topicLinkageHandler: topicLinkageHandler ?? undefined, threadlineRelayClient, threadlineReplyWaiters, listenerManager: listenerManager ?? undefined, responseReviewGate, messagingToneGate, outboundDedupGate, telemetryHeartbeat, pasteManager, featureRegistry, discoveryEvaluator, completionEvaluator, unifiedTrust, liveConfig, sharedStateLedger, ledgerSessionRegistry, worktreeManager, oidcEnrolledRepos: parallelDevConfig?.oidcEnrolledRepos, initiativeTracker, projectRoundRunner, projectDriftChecker, machineHeartbeat, machinePoolRegistry, meshRpcDispatcher, workingSetPullCoordinator, commitmentReplicaStore, forwardCommitmentMutate, sessionOwnershipRegistry, topicPinStore: _topicPinStore ?? undefined, secretSync: _secretSyncHandle ?? undefined, meshSelfId: _meshSelfId ?? undefined, resolveRouterUrl: _resolveRouterUrl ?? undefined, resolvePeerUrls: _resolvePeerUrls ?? undefined, sessionPoolE2EResultStore, proxyCoordinator, topicIntentStore, topicIntentArcCheck, usherSignalStore, intelligence: sharedIntelligence ?? undefined, telegramBridgeConfig, telegramBridge: telegramBridge ?? undefined, threadlineObservability, briefDeps, workingMemory, taskFlowRegistry, threadlineFlowBridge, sessionReaper, agentWorktreeReaper, mcpProcessReaper, geminiLoopRunner, sleepController, agentActivityState, reapLog, sleepWakeDetector, unjustifiedStopGate, stopGateDb, stopNotifier });
10934
+ // Resolve the late-bound topic-operator getter (increment 2e): routing was
10935
+ // wired before the server existed; from here on inbound binds use the
10936
+ // server's own store instance.
10937
+ _agentServerRef = server;
10900
10938
  // Boot-recovery (tunnel-failure-resilience spec Part 6): if the agent
10901
10939
  // died mid-relay-episode, the persisted tunnel.json carries
10902
10940
  // rotationPending=true. Rotate the dashboard PIN + authToken BEFORE