negotium 0.7.0 → 0.8.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.
Files changed (46) hide show
  1. package/README.md +3 -4
  2. package/dist/agent-helpers.js +17 -8
  3. package/dist/agent-helpers.js.map +10 -9
  4. package/dist/background-bash.js.map +2 -2
  5. package/dist/browser-runtime.js.map +2 -2
  6. package/dist/{chunk-9h53kw24.js → chunk-1bfta5qh.js} +2 -2
  7. package/dist/{chunk-9h53kw24.js.map → chunk-1bfta5qh.js.map} +2 -2
  8. package/dist/chunk-pp6dvrzq.js.map +2 -2
  9. package/dist/hosted-agent.js +2 -2
  10. package/dist/hosted-agent.js.map +4 -4
  11. package/dist/main.js +419 -150
  12. package/dist/main.js.map +19 -18
  13. package/dist/mcp-factories.js +17 -8
  14. package/dist/mcp-factories.js.map +10 -9
  15. package/dist/media.js.map +2 -2
  16. package/dist/prompts.js.map +2 -2
  17. package/dist/query-runtime.js +7 -2
  18. package/dist/query-runtime.js.map +7 -6
  19. package/dist/registry.js +1 -1
  20. package/dist/runtime/src/identifiers.ts +28 -0
  21. package/dist/runtime/src/index.ts +21 -2
  22. package/dist/runtime/src/node-host.ts +5 -1
  23. package/dist/runtime/src/query/index.ts +0 -1
  24. package/dist/runtime/src/query/public-runtime.ts +1 -5
  25. package/dist/runtime/src/query/room-query-registry.ts +4 -2
  26. package/dist/runtime/src/query/types.ts +0 -76
  27. package/dist/runtime/src/runtime/turn-runner.ts +4 -2
  28. package/dist/runtime/src/storage/api-topics.ts +32 -12
  29. package/dist/runtime/src/storage/storage-public.ts +4 -39
  30. package/dist/runtime/src/topics/personal-general.ts +3 -3
  31. package/dist/runtime/src/topics/update.ts +66 -1
  32. package/dist/runtime/src/types.ts +0 -11
  33. package/dist/runtime/src/version.ts +1 -1
  34. package/dist/runtime-helpers.js.map +2 -2
  35. package/dist/storage.js +11 -35
  36. package/dist/storage.js.map +4 -4
  37. package/dist/types/packages/core/src/identifiers.d.ts +21 -0
  38. package/dist/types/packages/core/src/query/public-runtime.d.ts +1 -1
  39. package/dist/types/packages/core/src/query/room-query-registry.d.ts +2 -1
  40. package/dist/types/packages/core/src/query/types.d.ts +0 -59
  41. package/dist/types/packages/core/src/storage/api-topics.d.ts +10 -4
  42. package/dist/types/packages/core/src/storage/storage-public.d.ts +2 -3
  43. package/dist/types/packages/core/src/types.d.ts +0 -10
  44. package/dist/types/packages/core/src/version.d.ts +1 -1
  45. package/dist/vault.js.map +2 -2
  46. package/package.json +1 -1
@@ -1,79 +1,3 @@
1
- import type { ForkHandle } from "#agents/fork";
2
- import type { AskReplySource } from "#storage/session-asks";
3
- import type { AgentKind, EffortLevel } from "#types";
4
-
5
- /**
6
- * What `handleAgentQuery` did with the request. Callers that own resources
7
- * tied to the params (e.g. an ask-fork rollout) use this to decide cleanup:
8
- * "ran"/"queued" transfer ownership to the query layer, "dropped" returns it.
9
- */
10
- export type HandleAgentQueryOutcome = "ran" | "queued" | "dropped";
11
-
12
- // --- Parameter interfaces ---
13
-
14
- interface BaseQueryParams {
15
- chatId: number;
16
- userId: number;
17
- topicName: string;
18
- sessionId: string | null;
19
- prompt: string;
20
- }
21
-
22
- interface OutputParams {
23
- messageThreadId?: number;
24
- systemPrompt: string;
25
- cwd?: string;
26
- sessionType?: "dm" | "forum" | "ephemeral" | "manager" | "cron";
27
- model?: string;
28
- silent?: boolean;
29
- effort?: EffortLevel;
30
- /** Override the topic-resolved agent backend. Used by callers like the
31
- * archiver that run on ephemeral topics and need an explicit provider. */
32
- agent?: AgentKind;
33
- }
34
-
35
- interface InterSessionParams {
36
- from?: string; // "user" or sender session name
37
- depth?: number; // 0 = from user, 1+ = via tell_session
38
- // For silent ask-reply forks: caller's depth at ask time. When the fork's
39
- // reply is injected back to the caller, the caller resumes at this depth
40
- // so tell chain caps remain accurate across ask hops.
41
- fromDepth?: number;
42
- requestId?: string; // unique ID for dedup in interSessionQueue
43
- contextId?: string; // context ID for multi-turn inter-session conversations
44
- /**
45
- * Ask-fork rollout backing this inject's `sessionId`. Ownership travels
46
- * WITH the params: while the inject sits in `interSessionQueue` the rollout
47
- * must stay on disk (deleting it breaks the dequeued query's resume), and
48
- * `handleAgentQuery`'s finally removes it once the consuming query actually
49
- * finished (and no retry/requeue still references it).
50
- */
51
- forkHandle?: ForkHandle;
52
- /** Original ask_session replies represented by this inject, preserved across dequeueAll merges. */
53
- askReplySources?: AskReplySource[];
54
- agents?: Record<
55
- string,
56
- {
57
- description: string;
58
- prompt: string;
59
- model?: string;
60
- tools?: string[];
61
- maxTurns?: number;
62
- effort?: EffortLevel | number;
63
- }
64
- >;
65
- }
66
-
67
- interface RetryGuardParams {
68
- _sessionRetried?: boolean; // guard against infinite retry on session expiry
69
- }
70
-
71
- export interface HandleAgentQueryParams
72
- extends BaseQueryParams,
73
- OutputParams,
74
- InterSessionParams,
75
- RetryGuardParams {}
76
-
77
1
  // --- Abort reason ---
78
2
 
79
3
  export enum AbortReason {
@@ -18,6 +18,7 @@ import {
18
18
  } from "#agents/mcp-tools/spawn-subagent";
19
19
  import { getRegistryOperations } from "#agents/registry";
20
20
  import { WsHub } from "#bus";
21
+ import { asTurnId, asTurnSlotKey, type TurnSlotKey } from "#identifiers";
21
22
  import { ensureBgBash } from "#platform/background-bash/manager";
22
23
  import { FROM_AUTO_CONTINUE } from "#platform/constants";
23
24
  import { logger } from "#platform/logger";
@@ -1031,8 +1032,9 @@ export function startAiTurn(params: StartAiTurnParams): string | null {
1031
1032
  const askReplySources = params.askReplySources;
1032
1033
  const sessionRetried = params._sessionRetried === true;
1033
1034
  const emptyResponseRetried = params._emptyResponseRetried === true;
1034
- const queryId = params._queryId ?? randomUUID();
1035
- const roomId = turnConcurrency === "isolated" ? isolatedTurnRoomId(topicId, queryId) : topicId;
1035
+ const queryId = asTurnId(params._queryId ?? randomUUID());
1036
+ const roomId: TurnSlotKey =
1037
+ turnConcurrency === "isolated" ? isolatedTurnRoomId(topicId, queryId) : asTurnSlotKey(topicId);
1036
1038
  const currentRuntimeEpoch = getRuntimeTopicEpoch(topic.id);
1037
1039
  const runtimeEpoch = params._runtimeEpoch ?? currentRuntimeEpoch;
1038
1040
  if (params._runtimeEpoch !== undefined && params._runtimeEpoch !== currentRuntimeEpoch) {
@@ -847,17 +847,16 @@ function normalizedTitle(title: string): string {
847
847
  /**
848
848
  * The workspace a written row belongs to.
849
849
  *
850
- * Only the `otium` surface has more than one instance, so terminal and telegram
851
- * are always null — writing this process's Otium scope onto a terminal room
852
- * would partition the terminal namespace for no reason. An explicit
853
- * `surfaceScope` in the DTO wins so a hub can file a room it already knows the
854
- * workspace of; otherwise the room joins whatever workspace this process is
855
- * attached to, which is null until the scope resolves (M-3).
850
+ * `surfaceScope` partitions one surface into independent namespaces. Otium
851
+ * uses a workspace scope and Telegram uses a forum-group scope. Terminal is
852
+ * normally unscoped. An explicit value always wins; only Otium has a
853
+ * process-level default because its workspace attachment is host state.
856
854
  */
857
855
  function surfaceScopeForWrite(t: TopicDto): string | null {
858
- if (normalizeTopicSurface(t.surface ?? defaultTopicSurface()) !== "otium") return null;
859
856
  if (t.surfaceScope !== undefined) return normalizeSurfaceScope(t.surfaceScope);
860
- return defaultSurfaceScope();
857
+ return normalizeTopicSurface(t.surface ?? defaultTopicSurface()) === "otium"
858
+ ? defaultSurfaceScope()
859
+ : null;
861
860
  }
862
861
 
863
862
  export function upsertTopic(t: TopicDto): void {
@@ -1067,10 +1066,10 @@ export function getTopicByNameAndKind(title: string, kind: TopicKind): TopicDto
1067
1066
  }
1068
1067
 
1069
1068
  /**
1070
- * Titles are unique **per surface instance**, not per node: `otium` may exist
1071
- * once on the terminal, once on telegram, and once in *each* attached Otium
1072
- * workspace (M-1). Two workspaces are two namespaces that never see each other,
1073
- * so a name taken in one says nothing about the other.
1069
+ * Titles are unique **per surface namespace**, not per node: the same title may
1070
+ * exist on terminal, in multiple Telegram groups, and in each attached Otium
1071
+ * workspace. Independent namespaces never see each other, so a name taken in
1072
+ * one says nothing about another.
1074
1073
  */
1075
1074
  export function findTopicTitleConflict(
1076
1075
  title: string,
@@ -1128,6 +1127,27 @@ export function setTopicSurfaces(topicIds: readonly string[], surface: TopicSurf
1128
1127
  return changed;
1129
1128
  }
1130
1129
 
1130
+ /**
1131
+ * File an existing topic into one surface namespace without changing its id.
1132
+ * Adapter-owned migrations use this when their local mapping store is the only
1133
+ * authority capable of deriving the namespace (for example Telegram chat id).
1134
+ */
1135
+ export function setTopicSurfaceScope(
1136
+ topicId: string,
1137
+ surface: TopicSurface,
1138
+ surfaceScope: string | null,
1139
+ ): boolean {
1140
+ const normalizedSurface = normalizeTopicSurface(surface);
1141
+ const normalizedScope = normalizeSurfaceScope(surfaceScope);
1142
+ const result = db
1143
+ .query(
1144
+ `UPDATE api_topics SET surface = ?, surface_scope = ?
1145
+ WHERE id = ? AND (surface IS NOT ? OR surface_scope IS NOT ?)`,
1146
+ )
1147
+ .run(normalizedSurface, normalizedScope, topicId, normalizedSurface, normalizedScope);
1148
+ return Number(result.changes ?? 0) > 0;
1149
+ }
1150
+
1131
1151
  /**
1132
1152
  * How wide a title lookup is allowed to reach.
1133
1153
  *
@@ -3,8 +3,8 @@
3
3
  // Namespaces preserve each legacy module's exact surface, including names that
4
4
  // collide across stores (notably forum.getTopicByName and apiTopics.getTopicByName).
5
5
  export * as activityLog from "#storage/activity-log";
6
- // Direct exports keep common replacements concise. The forum collision is
7
- // exposed as getForumTopicByName; its original name remains under `forum`.
6
+ // Direct exports keep common replacements concise. The legacy forum store
7
+ // remains available only under `forum`.
8
8
  export * from "#storage/activity-log";
9
9
  export * as apiMessages from "#storage/api-messages";
10
10
  export * from "#storage/api-messages";
@@ -22,43 +22,8 @@ export * as conversations from "#storage/conversations";
22
22
  export * from "#storage/conversations";
23
23
  export * as decisions from "#storage/decisions";
24
24
  export * from "#storage/decisions";
25
- export type {
26
- ForumTopicInfo,
27
- TopicRow,
28
- UserForumConfig,
29
- UserRow,
30
- } from "#storage/forum/index";
25
+ /** @deprecated Pre-canonical Telegram/forum compatibility namespace. */
31
26
  export * as forum from "#storage/forum/index";
32
- export {
33
- addTopic,
34
- clearDmSessionId,
35
- clearSessionForTopic,
36
- findUserByThread,
37
- flushSessionCache,
38
- getAllTopics,
39
- getAllUserIds,
40
- getCommunicateThreadId,
41
- getDmSessionId,
42
- getLastShownConfig,
43
- getSessionForTopic,
44
- getTopicAgent,
45
- getTopicByName as getForumTopicByName,
46
- getTopicDescription,
47
- getTopicMcpConfig,
48
- getTopicNames,
49
- getUserConfig,
50
- removeTopic,
51
- renameTopic,
52
- setDmSessionId,
53
- setLastShownConfig,
54
- setSessionForTopic,
55
- setTopicAgent,
56
- setTopicDescription,
57
- setTopicForkOrigin,
58
- setTopicMcpEnabled,
59
- setTopicMcpExtra,
60
- updateTopicThreadId,
61
- } from "#storage/forum/index";
62
27
  export * as runtimeProcessLeases from "#storage/runtime-process-leases";
63
28
  export * from "#storage/runtime-process-leases";
64
29
  export * as sessionAsks from "#storage/session-asks";
@@ -81,8 +46,8 @@ export * as topicArchive from "#storage/topic-archive";
81
46
  export * from "#storage/topic-archive";
82
47
  export * as topicArchiveState from "#storage/topic-archive-state";
83
48
  export * from "#storage/topic-archive-state";
49
+ /** @deprecated Pre-canonical topic-name settings compatibility namespace. */
84
50
  export * as topicSettings from "#storage/topic-settings";
85
- export * from "#storage/topic-settings";
86
51
  export * as topicTranscript from "#storage/topic-transcript";
87
52
  export * from "#storage/topic-transcript";
88
53
  export * as wiki from "#storage/wiki";
@@ -31,9 +31,9 @@ export function ensurePersonalGeneral(
31
31
  opts: { surfaceScope?: string | null } = {},
32
32
  ): TopicDto {
33
33
  const scope = normalizeTopicSurface(surface ?? defaultTopicSurface());
34
- // One General per user *per workspace*. A manager room is exempt from title
35
- // conflicts precisely because several may share the name, and two workspaces
36
- // sharing one private room would merge two customers' transcripts.
34
+ // One General per user *per surface namespace*. Otium namespaces by
35
+ // workspace and Telegram by forum group; sharing one manager across either
36
+ // boundary would merge unrelated transcripts and provider sessions.
37
37
  const surfaceScope =
38
38
  opts.surfaceScope !== undefined
39
39
  ? normalizeSurfaceScope(opts.surfaceScope)
@@ -14,15 +14,17 @@ import { resolveModelForAgent } from "#agents/model-catalog";
14
14
  import { getRegistry } from "#agents/registry";
15
15
  import { WsHub } from "#bus";
16
16
  import { RESERVED_TOPIC_NAMES } from "#platform/constants";
17
- import { getApiTopicConfig, setApiTopicConfig } from "#storage/api-topic-config";
17
+ import { getApiTopicConfig, setApiTopicConfig, type TopicConfig } from "#storage/api-topic-config";
18
18
  import {
19
19
  findTopicTitleConflict,
20
20
  getTopic,
21
21
  normalizeAiMode,
22
22
  normalizeTopicKind,
23
23
  normalizeTopicState,
24
+ setApiTopicAgent,
24
25
  upsertTopic,
25
26
  } from "#storage/api-topics";
27
+ import { db } from "#storage/forum-db";
26
28
  import { TopicValidationError } from "#topics/create";
27
29
  import { type AgentKind, type EffortLevel, isAgentKind } from "#types";
28
30
  import type { AiMode, TopicDto } from "#types/api";
@@ -42,6 +44,69 @@ export interface UpdateTopicSettingsOptions {
42
44
  aiMode?: AiMode;
43
45
  }
44
46
 
47
+ export interface UpdateManagerTopicRuntimeConfigOptions {
48
+ topicId: string;
49
+ agent: AgentKind;
50
+ config: TopicConfig;
51
+ }
52
+
53
+ /**
54
+ * Atomically update the execution settings of a system-managed General room.
55
+ * Its identity fields remain protected by updateTopicSettings; only the
56
+ * canonical agent/defaults and per-topic override move together here.
57
+ */
58
+ export function updateManagerTopicRuntimeConfig(
59
+ opts: UpdateManagerTopicRuntimeConfigOptions,
60
+ ): TopicDto {
61
+ const current = getTopic(opts.topicId);
62
+ if (!current) throw new TopicValidationError("Topic not found");
63
+ if (current.kind !== "manager") {
64
+ throw new TopicValidationError("Runtime config agent updates are manager-only");
65
+ }
66
+ if (!isAgentKind(opts.agent)) throw new TopicValidationError(`Unknown agent '${opts.agent}'`);
67
+
68
+ const registry = getRegistry(opts.agent);
69
+ if (
70
+ opts.config.model &&
71
+ resolveModelForAgent(opts.agent, opts.config.model, registry) !== opts.config.model
72
+ ) {
73
+ throw new TopicValidationError(`Invalid model for agent ${opts.agent}`);
74
+ }
75
+ if (opts.config.effort && !registry.validateEffort(opts.config.effort)) {
76
+ throw new TopicValidationError(`Invalid effort for agent ${opts.agent}`);
77
+ }
78
+
79
+ const defaultModel = resolveModelForAgent(
80
+ opts.agent,
81
+ opts.config.model ?? (opts.agent === current.agent ? current.defaultModel : undefined),
82
+ registry,
83
+ );
84
+ const requestedEffort =
85
+ opts.config.effort ?? (opts.agent === current.agent ? current.defaultEffort : undefined);
86
+ const defaultEffort =
87
+ requestedEffort && registry.validateEffort(requestedEffort)
88
+ ? requestedEffort
89
+ : (registry.defaultEffort ?? "medium");
90
+
91
+ db.transaction(() => {
92
+ setApiTopicAgent(current.id, opts.agent, {
93
+ model: defaultModel,
94
+ effort: defaultEffort,
95
+ });
96
+ setApiTopicConfig(current.id, opts.config);
97
+ })();
98
+
99
+ WsHub.get().broadcastTopicUpdated(current.id);
100
+ return (
101
+ getTopic(current.id) ?? {
102
+ ...current,
103
+ agent: opts.agent,
104
+ defaultModel,
105
+ defaultEffort,
106
+ }
107
+ );
108
+ }
109
+
45
110
  /** A title that is already taken by another room on the same surface. */
46
111
  export class TopicUpdateConflictError extends Error {
47
112
  constructor(message: string) {
@@ -1,14 +1,3 @@
1
- /**
2
- * Common context carried through the attachment/prompt-build pipeline.
3
- * Used by buildPromptFromMessage and related helpers.
4
- */
5
- export interface SessionContext {
6
- userId: number;
7
- topicName?: string;
8
- userDir?: string;
9
- sessionType?: "dm" | "forum" | "ephemeral" | "manager" | "cron";
10
- }
11
-
12
1
  export interface TokenUsage {
13
2
  /** Aggregate billable input across every model call made during this turn. */
14
3
  inputTokens: number;
@@ -1 +1 @@
1
- export const NEGOTIUM_VERSION = "0.7.0";
1
+ export const NEGOTIUM_VERSION = "0.8.0";