@unieai/rabi-api-session-controller 0.0.0-stage → 0.2.2-rc.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +7 -2
- package/lib/client.js +4 -0
- package/lib/index.js +4300 -0
- package/lib/typert.host.d.ts +3 -0
- package/lib/typert.host.js +5013 -0
- package/lib/typert.remote-client.d.ts +115 -0
- package/lib/typert.remote-client.js +2714 -0
- package/lib/types/agent.d.ts +164 -0
- package/lib/types/agent.js +484 -0
- package/lib/types/archived-session-gate.d.ts +33 -0
- package/lib/types/archived-session-gate.js +54 -0
- package/lib/types/assistant-stream.d.ts +26 -0
- package/lib/types/assistant-stream.js +82 -0
- package/lib/types/catalog.d.ts +24 -0
- package/lib/types/catalog.js +107 -0
- package/lib/types/client/contract/events.d.ts +102 -0
- package/lib/types/client/contract/events.js +111 -0
- package/lib/types/client/contract/session.d.ts +178 -0
- package/lib/types/client/contract/session.js +1 -0
- package/lib/types/client/contract/sessions.d.ts +162 -0
- package/lib/types/client/contract/sessions.js +1 -0
- package/lib/types/client/contract/snapshot.d.ts +84 -0
- package/lib/types/client/contract/snapshot.js +1 -0
- package/lib/types/client/index.d.ts +39 -0
- package/lib/types/client/index.js +60 -0
- package/lib/types/client/ordered-baseline.d.ts +12 -0
- package/lib/types/client/ordered-baseline.js +40 -0
- package/lib/types/client/scope.d.ts +46 -0
- package/lib/types/client/scope.js +46 -0
- package/lib/types/client/session-wire-event.d.ts +11 -0
- package/lib/types/client/session-wire-event.js +42 -0
- package/lib/types/client/sessions/assistant-stream.d.ts +56 -0
- package/lib/types/client/sessions/assistant-stream.js +182 -0
- package/lib/types/client/sessions/history-records.d.ts +22 -0
- package/lib/types/client/sessions/history-records.js +25 -0
- package/lib/types/client/sessions/lineage.d.ts +48 -0
- package/lib/types/client/sessions/lineage.js +55 -0
- package/lib/types/client/sessions/manager.d.ts +272 -0
- package/lib/types/client/sessions/manager.js +774 -0
- package/lib/types/client/sessions/notifier.d.ts +39 -0
- package/lib/types/client/sessions/notifier.js +97 -0
- package/lib/types/client/sessions/projection-store.d.ts +128 -0
- package/lib/types/client/sessions/projection-store.js +161 -0
- package/lib/types/client/sessions/remotes.d.ts +29 -0
- package/lib/types/client/sessions/remotes.js +7 -0
- package/lib/types/client/sessions/service.d.ts +263 -0
- package/lib/types/client/sessions/service.js +597 -0
- package/lib/types/client/sessions/session.d.ts +303 -0
- package/lib/types/client/sessions/session.js +991 -0
- package/lib/types/client/time-zone.d.ts +8 -0
- package/lib/types/client/time-zone.js +13 -0
- package/lib/types/client/transport.d.ts +77 -0
- package/lib/types/client/transport.js +130 -0
- package/lib/types/commands.d.ts +92 -0
- package/lib/types/commands.js +575 -0
- package/lib/types/continuation.d.ts +35 -0
- package/lib/types/continuation.js +47 -0
- package/lib/types/control.d.ts +20 -0
- package/lib/types/control.js +106 -0
- package/lib/types/file-references.d.ts +27 -0
- package/lib/types/file-references.js +68 -0
- package/lib/types/history/assistant-stream.d.ts +43 -0
- package/lib/types/history/assistant-stream.js +79 -0
- package/lib/types/history/controller.d.ts +104 -0
- package/lib/types/history/controller.js +293 -0
- package/lib/types/history/listener.d.ts +105 -0
- package/lib/types/history/listener.js +296 -0
- package/lib/types/history.d.ts +58 -0
- package/lib/types/history.js +152 -0
- package/lib/types/index.d.ts +262 -0
- package/lib/types/index.js +693 -0
- package/lib/types/list.d.ts +62 -0
- package/lib/types/list.js +343 -0
- package/lib/types/media-references.d.ts +18 -0
- package/lib/types/media-references.js +84 -0
- package/lib/types/remote-events.d.ts +8 -0
- package/lib/types/remote-events.js +1 -0
- package/lib/types/skill-catalog.d.ts +28 -0
- package/lib/types/skill-catalog.js +203 -0
- package/lib/types/state/controller.d.ts +45 -0
- package/lib/types/state/controller.js +288 -0
- package/lib/types/state/listener.d.ts +40 -0
- package/lib/types/state/listener.js +111 -0
- package/lib/types/types.d.ts +687 -0
- package/lib/types/types.js +5 -0
- package/lib/types/web/controller.d.ts +25 -0
- package/lib/types/web/controller.js +138 -0
- package/locale/de.json +6 -0
- package/locale/en.json +5 -0
- package/locale/es.json +6 -0
- package/locale/fr.json +6 -0
- package/locale/ja.json +6 -0
- package/locale/pt.json +6 -0
- package/locale/ru.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +119 -4
- package/src/agent.ts +474 -0
- package/src/archived-session-gate.ts +59 -0
- package/src/assistant-stream.ts +102 -0
- package/src/catalog.ts +117 -0
- package/src/client/contract/events.ts +205 -0
- package/src/client/contract/session.ts +174 -0
- package/src/client/contract/sessions.ts +169 -0
- package/src/client/contract/snapshot.ts +94 -0
- package/src/client/index.ts +149 -0
- package/src/client/ordered-baseline.ts +43 -0
- package/src/client/scope.ts +76 -0
- package/src/client/session-wire-event.ts +46 -0
- package/src/client/sessions/assistant-stream.ts +229 -0
- package/src/client/sessions/history-records.ts +35 -0
- package/src/client/sessions/lineage.ts +96 -0
- package/src/client/sessions/manager.ts +857 -0
- package/src/client/sessions/notifier.ts +97 -0
- package/src/client/sessions/projection-store.ts +244 -0
- package/src/client/sessions/remotes.ts +44 -0
- package/src/client/sessions/service.ts +741 -0
- package/src/client/sessions/session.ts +1055 -0
- package/src/client/time-zone.ts +14 -0
- package/src/client/transport.ts +247 -0
- package/src/commands.ts +602 -0
- package/src/continuation.ts +58 -0
- package/src/control.ts +121 -0
- package/src/file-references.ts +42 -0
- package/src/history/assistant-stream.ts +102 -0
- package/src/history/controller.ts +256 -0
- package/src/history/listener.ts +302 -0
- package/src/history.ts +189 -0
- package/src/index.ts +651 -0
- package/src/list.ts +382 -0
- package/src/media-references.ts +84 -0
- package/src/remote-events.ts +14 -0
- package/src/skill-catalog.ts +108 -0
- package/src/state/controller.ts +221 -0
- package/src/state/listener.ts +116 -0
- package/src/types.ts +720 -0
- package/src/web/controller.ts +78 -0
package/src/commands.ts
ADDED
|
@@ -0,0 +1,602 @@
|
|
|
1
|
+
/** Session commands whose activation policy is explicit at each Remote method. */
|
|
2
|
+
|
|
3
|
+
import type { ProjectionHandle } from '@unieai/rabi-session-projection'
|
|
4
|
+
import { continuationProjectionDefinition, type ContinuationState } from './continuation.ts'
|
|
5
|
+
|
|
6
|
+
import { modelAvailable } from './catalog.ts'
|
|
7
|
+
import { randomUUID } from 'node:crypto'
|
|
8
|
+
import type { Context } from '@unieai/cordis'
|
|
9
|
+
import { brandString } from '@unieai/rabi-brand'
|
|
10
|
+
import type { Agent, ModelSelection as AgentModelSelection } from '@unieai/rabi-agent'
|
|
11
|
+
import { AttachmentError } from '@unieai/rabi-attachment'
|
|
12
|
+
import type {
|
|
13
|
+
AttachmentAdmissionPart,
|
|
14
|
+
} from '@unieai/rabi-attachment'
|
|
15
|
+
import type { FileUploadReceiptId, StagedAttachment } from '@unieai/rabi-client-file-upload/types'
|
|
16
|
+
import type {} from '@unieai/rabi-client-file-upload'
|
|
17
|
+
import {
|
|
18
|
+
ReasoningEffortId, createUserMessage, freezeMessage,
|
|
19
|
+
} from '@unieai/rabi-llm'
|
|
20
|
+
import type { MessageId, MessageSource } from '@unieai/rabi-llm'
|
|
21
|
+
import { buildForkSeed } from '@unieai/rabi-session/fork'
|
|
22
|
+
import { SessionLogOffset, SessionSeq } from '@unieai/rabi-session'
|
|
23
|
+
import type { Session, SessionEvent, SessionHeader, SessionId, UserMessage } from '@unieai/rabi-session'
|
|
24
|
+
import { SessionQueryError, type SessionObservation } from '@unieai/rabi-session-query'
|
|
25
|
+
import { SessionTitleInvalidError } from '@unieai/rabi-session-title'
|
|
26
|
+
import { assertNever } from '@unieai/rabi-util-values'
|
|
27
|
+
import { RemoteError, remoteErrorOf } from '@unieai/rabi-typert-protocol'
|
|
28
|
+
import type { Workspace } from '@unieai/rabi-workspace'
|
|
29
|
+
import {
|
|
30
|
+
ApiSessionAgentController,
|
|
31
|
+
ApiSessionCwdConflict,
|
|
32
|
+
ApiSessionPresetConflict,
|
|
33
|
+
ApiSessionSubagentOwnership,
|
|
34
|
+
apiSessionSubagentOwnershipError,
|
|
35
|
+
hasApiSessionSubagentOwner,
|
|
36
|
+
type ApiSessionCreated,
|
|
37
|
+
} from './agent.ts'
|
|
38
|
+
import type {
|
|
39
|
+
SessionAttachmentRequest,
|
|
40
|
+
SessionAttachmentValue,
|
|
41
|
+
SessionCancelRequest,
|
|
42
|
+
SessionCancelValue,
|
|
43
|
+
SessionCreateRequest,
|
|
44
|
+
SessionCreateValue,
|
|
45
|
+
SessionForkRequest,
|
|
46
|
+
SessionForkValue,
|
|
47
|
+
SessionPromptRequest,
|
|
48
|
+
SessionPromptValue,
|
|
49
|
+
SessionRenameRequest,
|
|
50
|
+
SessionRenameValue,
|
|
51
|
+
SessionSelectModelRequest,
|
|
52
|
+
SessionSelectModelValue,
|
|
53
|
+
SessionUpdateQueueRequest,
|
|
54
|
+
SessionUpdateQueueValue,
|
|
55
|
+
SessionRequestId,
|
|
56
|
+
} from './types.ts'
|
|
57
|
+
|
|
58
|
+
type PromptContentCandidate =
|
|
59
|
+
| SessionPromptRequest['content'][number]
|
|
60
|
+
| Extract<SessionUpdateQueueRequest['action'], { readonly kind: 'edit' }>['content'][number]
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Whether prompt content carries non-whitespace text or an attachment.
|
|
64
|
+
* @param content - submitted or edited prompt parts.
|
|
65
|
+
* @returns whether any part supplies ordinary prompt content.
|
|
66
|
+
*/
|
|
67
|
+
export function hasPromptContent(content: readonly PromptContentCandidate[]): boolean {
|
|
68
|
+
return content.some(part => part.type !== 'text' || part.text.trim().length > 0)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Resolve the omitted-`atSeq` default to the latest completed-turn prefix,
|
|
73
|
+
* including standalone events before the next turn begins.
|
|
74
|
+
*/
|
|
75
|
+
function latestCompletedPrefixBoundary(events: readonly SessionEvent[]): SessionSeq | undefined {
|
|
76
|
+
const lastTurnEnd = events.findLast(event => event.type === 'turn/end')
|
|
77
|
+
if (lastTurnEnd === undefined) return undefined
|
|
78
|
+
let boundary = lastTurnEnd.seq
|
|
79
|
+
for (const next of events.slice(boundary + 1)) {
|
|
80
|
+
if (next.type === 'turn/start' || (next.type === 'user/message' && next.surfaceOp === 'append')
|
|
81
|
+
|| next.type === 'agent/inbox/spliced') break
|
|
82
|
+
boundary = next.seq
|
|
83
|
+
}
|
|
84
|
+
return boundary
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Implements Session business commands delegated by the Session Controller Remote service. */
|
|
88
|
+
export class SessionCommandController {
|
|
89
|
+
/** First-insertion facts cached per exact Session; the log remains the recovery source. */
|
|
90
|
+
private readonly promptReceipts = new WeakMap<Session, {
|
|
91
|
+
offset: SessionLogOffset
|
|
92
|
+
messages: Set<MessageId>
|
|
93
|
+
requests: Set<SessionRequestId>
|
|
94
|
+
}>()
|
|
95
|
+
|
|
96
|
+
private continuation!: ProjectionHandle<ContinuationState>
|
|
97
|
+
|
|
98
|
+
/** Register complete-history empty-prompt eligibility. @returns when command admission is ready. */
|
|
99
|
+
async initialize(): Promise<void> {
|
|
100
|
+
this.continuation = await this.ctx.sessionProjections.register(continuationProjectionDefinition)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* @param ctx - Host context carrying Agent, model, attachment, title, and Workspace services.
|
|
105
|
+
* @param agents - sole owner of create, resume, and Agent composition.
|
|
106
|
+
* @param defaultCwd - project directory used when create names neither a Workspace nor a cwd.
|
|
107
|
+
*/
|
|
108
|
+
constructor(
|
|
109
|
+
private readonly ctx: Context,
|
|
110
|
+
private readonly agents: ApiSessionAgentController,
|
|
111
|
+
private readonly defaultCwd: string,
|
|
112
|
+
) {}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Create one ordinary Session for a new conversation, reusing the named
|
|
116
|
+
* blank Session while it is an unarchived member of the requested Workspace.
|
|
117
|
+
* @param request - optional blank Session to reuse, location, and Agent preset.
|
|
118
|
+
* @returns the created or reused Session identity and its preset when configured.
|
|
119
|
+
*/
|
|
120
|
+
async create(request: SessionCreateRequest): Promise<SessionCreateValue> {
|
|
121
|
+
if (request.workspaceId !== undefined && request.cwd !== undefined) {
|
|
122
|
+
throw new RemoteError('gateway/bad-request', 'session.create accepts workspaceId or cwd, not both', {})
|
|
123
|
+
}
|
|
124
|
+
let workspace: Workspace | undefined
|
|
125
|
+
if (request.workspaceId !== undefined) {
|
|
126
|
+
workspace = this.ctx.workspaceRegistry.get(request.workspaceId)
|
|
127
|
+
if (workspace === undefined) {
|
|
128
|
+
throw new RemoteError('workspace/not-found', `workspace "${request.workspaceId}" not found`, {
|
|
129
|
+
workspaceId: request.workspaceId,
|
|
130
|
+
})
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
const cwd = workspace?.path ?? request.cwd ?? this.defaultCwd
|
|
134
|
+
let created: ApiSessionCreated
|
|
135
|
+
try {
|
|
136
|
+
created = await this.agents.createSession({
|
|
137
|
+
...(request.sessionId === undefined ? {} : { sessionId: request.sessionId }),
|
|
138
|
+
cwd,
|
|
139
|
+
...(request.agentPreset === undefined ? {} : { agentPreset: request.agentPreset }),
|
|
140
|
+
reusable: sessionId => !this.ctx.workspaceRegistry.archivedSessionIds.includes(sessionId)
|
|
141
|
+
&& (workspace === undefined || workspace.sessionIds.includes(sessionId)),
|
|
142
|
+
})
|
|
143
|
+
} catch (error) {
|
|
144
|
+
this.rejectCreation(error)
|
|
145
|
+
}
|
|
146
|
+
const sessionId = created.agent.id
|
|
147
|
+
if (workspace !== undefined) {
|
|
148
|
+
try {
|
|
149
|
+
await workspace.attachSession(sessionId)
|
|
150
|
+
} catch (error) {
|
|
151
|
+
throw new RemoteError(
|
|
152
|
+
'session/workspace-attach-failed',
|
|
153
|
+
`session "${sessionId}" was created but could not attach to workspace "${workspace.id}": ${String(error)}`,
|
|
154
|
+
{ sessionId, workspaceId: workspace.id },
|
|
155
|
+
)
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return { sessionId, ...(created.agentPreset === undefined ? {} : { agentPreset: created.agentPreset }) }
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Validate and record one Session model selection; save the default in the background.
|
|
163
|
+
* @param request - Session identity and requested model selection.
|
|
164
|
+
* @returns the normalized selection recorded for the Session, without waiting for default persistence.
|
|
165
|
+
*/
|
|
166
|
+
async selectModel(request: SessionSelectModelRequest): Promise<SessionSelectModelValue> {
|
|
167
|
+
const agent = await this.resolveAgent(request.sessionId)
|
|
168
|
+
return this.agents.serializeImageAdmission(agent, async () => {
|
|
169
|
+
try {
|
|
170
|
+
await this.requireModel(request)
|
|
171
|
+
const selected: AgentModelSelection = {
|
|
172
|
+
provider: request.provider,
|
|
173
|
+
model: request.model,
|
|
174
|
+
...(request.reasoningEffort === undefined
|
|
175
|
+
? {}
|
|
176
|
+
: { reasoningEffort: ReasoningEffortId(request.reasoningEffort) }),
|
|
177
|
+
}
|
|
178
|
+
await this.ctx.llm.resolveCallConfig(selected)
|
|
179
|
+
agent.model.select(selected)
|
|
180
|
+
void this.ctx.agentDefaultModel.saveSelection(selected).catch((error: unknown) => {
|
|
181
|
+
this.ctx.logger.warn(
|
|
182
|
+
`session-controller: model selection changed for the Session but the default was not saved: ${String(error)}`,
|
|
183
|
+
)
|
|
184
|
+
})
|
|
185
|
+
return { selected: { ...selected } }
|
|
186
|
+
} catch (error) {
|
|
187
|
+
if (remoteErrorOf(error) !== undefined) throw error
|
|
188
|
+
throw new RemoteError(
|
|
189
|
+
'session/model-unavailable',
|
|
190
|
+
error instanceof Error ? error.message : String(error),
|
|
191
|
+
{ provider: request.provider, model: request.model },
|
|
192
|
+
)
|
|
193
|
+
}
|
|
194
|
+
})
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Normalize and append a user-owned Session title.
|
|
199
|
+
* @param request - Session identity and proposed title.
|
|
200
|
+
* @returns the accepted title and durable event sequence.
|
|
201
|
+
*/
|
|
202
|
+
async rename(request: SessionRenameRequest): Promise<SessionRenameValue> {
|
|
203
|
+
const agent = await this.resolveAgent(request.sessionId)
|
|
204
|
+
const titles = this.ctx.get('sessionTitle')
|
|
205
|
+
if (titles === undefined) {
|
|
206
|
+
throw new RemoteError('gateway/internal', 'renaming is unavailable: this deployment mounts no session-title service', {})
|
|
207
|
+
}
|
|
208
|
+
try {
|
|
209
|
+
const accepted = titles.rename(agent.session, request.title)
|
|
210
|
+
return { title: accepted.title, seq: accepted.eventSeq }
|
|
211
|
+
} catch (error) {
|
|
212
|
+
if (error instanceof SessionTitleInvalidError) {
|
|
213
|
+
throw new RemoteError('session/title-invalid', error.message, { sessionId: request.sessionId })
|
|
214
|
+
}
|
|
215
|
+
throw new RemoteError(
|
|
216
|
+
'gateway/internal',
|
|
217
|
+
`failed to rename session "${request.sessionId}": ${String(error)}`,
|
|
218
|
+
{},
|
|
219
|
+
)
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Create a new ordinary Session from an exact event prefix. An explicit
|
|
225
|
+
* `atSeq` is the inclusive cut; an omitted value selects the latest
|
|
226
|
+
* completed-turn prefix. An open cut receives synthetic fork closers.
|
|
227
|
+
* @param request - source Session and optional exact event boundary.
|
|
228
|
+
* @returns the new Session identity.
|
|
229
|
+
*/
|
|
230
|
+
async fork(request: SessionForkRequest): Promise<SessionForkValue> {
|
|
231
|
+
let atSeq: ReturnType<typeof SessionSeq> | undefined
|
|
232
|
+
try {
|
|
233
|
+
atSeq = request.atSeq === undefined ? undefined : SessionSeq(request.atSeq)
|
|
234
|
+
} catch {
|
|
235
|
+
throw new RemoteError('gateway/bad-request', 'atSeq must be a non-negative safe integer', {})
|
|
236
|
+
}
|
|
237
|
+
let observed: SessionObservation
|
|
238
|
+
try {
|
|
239
|
+
observed = await this.ctx.sessionQuery.observeSession(request.sessionId)
|
|
240
|
+
} catch (error) {
|
|
241
|
+
if (error instanceof SessionQueryError
|
|
242
|
+
&& error.code === 'SESSION_QUERY_SESSION_NOT_FOUND') {
|
|
243
|
+
throw new RemoteError('session/not-found', `session "${request.sessionId}" not found`, {
|
|
244
|
+
sessionId: request.sessionId,
|
|
245
|
+
})
|
|
246
|
+
}
|
|
247
|
+
throw new RemoteError(
|
|
248
|
+
'gateway/internal',
|
|
249
|
+
`fork source unavailable for session "${request.sessionId}": ${String(error)}`,
|
|
250
|
+
{},
|
|
251
|
+
)
|
|
252
|
+
}
|
|
253
|
+
using source = observed
|
|
254
|
+
const boundary = atSeq ?? latestCompletedPrefixBoundary(source.events)
|
|
255
|
+
if (boundary === undefined || source.events[boundary]?.seq !== boundary) {
|
|
256
|
+
throw new RemoteError(
|
|
257
|
+
'session/fork-unavailable',
|
|
258
|
+
request.atSeq === undefined
|
|
259
|
+
? `session "${request.sessionId}" has no completed turn to fork from`
|
|
260
|
+
: `event ${String(request.atSeq)} does not exist in session "${request.sessionId}" (last seq: ${String(source.events.at(-1)?.seq ?? 'none')})`,
|
|
261
|
+
{ sessionId: request.sessionId },
|
|
262
|
+
)
|
|
263
|
+
}
|
|
264
|
+
const seed = buildForkSeed(source.events, boundary)
|
|
265
|
+
let workspace: Workspace | undefined
|
|
266
|
+
try {
|
|
267
|
+
workspace = await this.forkWorkspace(source.header)
|
|
268
|
+
} catch (error) {
|
|
269
|
+
throw new RemoteError(
|
|
270
|
+
'gateway/internal',
|
|
271
|
+
`failed to resolve fork workspace for session "${request.sessionId}": ${String(error)}`,
|
|
272
|
+
{},
|
|
273
|
+
)
|
|
274
|
+
}
|
|
275
|
+
const childId = brandString<SessionId>(`session-${randomUUID()}`)
|
|
276
|
+
const composition = await this.agents.composeAgent(this.agents.presetForObservation(source))
|
|
277
|
+
try {
|
|
278
|
+
const { provider, model } = this.ctx.agentDefaultModel.currentSelection()
|
|
279
|
+
await this.ctx.agents.create({
|
|
280
|
+
sessionId: childId,
|
|
281
|
+
seed,
|
|
282
|
+
inheritedEventCount: SessionLogOffset(boundary + 1),
|
|
283
|
+
meta: {
|
|
284
|
+
...(source.header.cwd === undefined ? {} : { cwd: source.header.cwd }),
|
|
285
|
+
isSeeded: true,
|
|
286
|
+
...(composition.agentPreset === undefined
|
|
287
|
+
? {}
|
|
288
|
+
: { agentPreset: composition.agentPreset }),
|
|
289
|
+
},
|
|
290
|
+
agentOptions: { provider, model },
|
|
291
|
+
setup: composition.setup,
|
|
292
|
+
})
|
|
293
|
+
} catch (error) {
|
|
294
|
+
throw new RemoteError(
|
|
295
|
+
'gateway/internal',
|
|
296
|
+
`failed to fork session "${request.sessionId}": ${String(error)}`,
|
|
297
|
+
{},
|
|
298
|
+
)
|
|
299
|
+
}
|
|
300
|
+
if (workspace !== undefined) {
|
|
301
|
+
try {
|
|
302
|
+
await workspace.attachSession(childId)
|
|
303
|
+
} catch (error) {
|
|
304
|
+
throw new RemoteError(
|
|
305
|
+
'session/workspace-attach-failed',
|
|
306
|
+
`session "${childId}" was forked but could not attach to workspace "${workspace.id}": ${String(error)}`,
|
|
307
|
+
{ sessionId: childId, workspaceId: workspace.id },
|
|
308
|
+
)
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
return { sessionId: childId }
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* Admit one prompt after Agent and attachment validation; the Remote method
|
|
316
|
+
* has already validated the content and built the durable message source.
|
|
317
|
+
* @param request - Session identity, prompt content, and delivery mode.
|
|
318
|
+
* @param source - caller metadata recorded on the accepted ordinary or retry user message.
|
|
319
|
+
* @returns acknowledgement that the Agent accepted the prompt.
|
|
320
|
+
*/
|
|
321
|
+
async prompt(request: SessionPromptRequest, source: MessageSource): Promise<SessionPromptValue> {
|
|
322
|
+
const agent = await this.resolveAgent(request.sessionId)
|
|
323
|
+
if (this.hasPromptRequest(agent.session, request.requestId)) return { accepted: true }
|
|
324
|
+
if (request.content.length === 0) {
|
|
325
|
+
try {
|
|
326
|
+
return await agent.runMaintenance(() => {
|
|
327
|
+
const inbox = agent.inbox
|
|
328
|
+
if (request.mode !== 'queue' || this.continuation.stateOf(agent.session).ending === null
|
|
329
|
+
|| inbox.nextTurn.length > 0 || inbox.nextStep.some(message => message.source.kind === 'user')) {
|
|
330
|
+
throw new RemoteError('session/agent-busy', 'generation continuation is unavailable', { reason: 'NO_CONTINUABLE_FAILURE_OR_PENDING_INPUT' })
|
|
331
|
+
}
|
|
332
|
+
agent.followup(createUserMessage({ content: [], source }))
|
|
333
|
+
return Promise.resolve({ accepted: true as const })
|
|
334
|
+
})
|
|
335
|
+
} catch (error: unknown) {
|
|
336
|
+
if (remoteErrorOf(error) !== undefined) throw error
|
|
337
|
+
throw new RemoteError('session/agent-busy', 'generation continuation was not accepted', { reason: String(error) })
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
const admission = resolvePromptFileReceipts(
|
|
341
|
+
request.content,
|
|
342
|
+
receiptId => this.ctx.fileUploads.resolve(agent, receiptId),
|
|
343
|
+
)
|
|
344
|
+
// Encoded images and image upload receipts both make an image prompt.
|
|
345
|
+
const hasImage = admission.content.some(part => part.type === 'image')
|
|
346
|
+
const admit = async (): Promise<SessionPromptValue> => {
|
|
347
|
+
try {
|
|
348
|
+
if (this.hasPromptRequest(agent.session, request.requestId)) return { accepted: true }
|
|
349
|
+
if (hasImage) {
|
|
350
|
+
const current = agent.model.current()
|
|
351
|
+
if (current !== undefined) {
|
|
352
|
+
const model = await this.ctx.llm.resolveModelInfo(current.provider, current.model)
|
|
353
|
+
if (model.inputModalities !== undefined && !model.inputModalities.includes('image')) {
|
|
354
|
+
throw new RemoteError(
|
|
355
|
+
'session/attachment-invalid',
|
|
356
|
+
`Model "${current.model}" does not support image input.`,
|
|
357
|
+
{ reason: 'MODEL_DOES_NOT_SUPPORT_IMAGES' },
|
|
358
|
+
)
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
const content = await this.ctx.attachments.admitPromptContent(admission.content)
|
|
363
|
+
if (this.hasPromptRequest(agent.session, request.requestId)) return { accepted: true }
|
|
364
|
+
const message: UserMessage = createUserMessage({ content, source })
|
|
365
|
+
if (this.ctx.agents.get(agent.id) !== agent) {
|
|
366
|
+
throw new RemoteError(
|
|
367
|
+
'session/not-found',
|
|
368
|
+
`session "${agent.id}" was disposed during prompt admission`,
|
|
369
|
+
{ sessionId: agent.id },
|
|
370
|
+
)
|
|
371
|
+
}
|
|
372
|
+
using binding = this.ctx.fileUploads.bindPrompt(agent, admission.receiptIds, request.requestId)
|
|
373
|
+
if (request.mode === 'steer') agent.steer(message)
|
|
374
|
+
else agent.followup(message)
|
|
375
|
+
binding.commit()
|
|
376
|
+
} catch (error) {
|
|
377
|
+
if (this.hasPromptRequest(agent.session, request.requestId)) return { accepted: true }
|
|
378
|
+
if (remoteErrorOf(error) !== undefined) throw error
|
|
379
|
+
if (error instanceof AttachmentError) {
|
|
380
|
+
throw new RemoteError('session/attachment-invalid', error.message, { reason: error.code })
|
|
381
|
+
}
|
|
382
|
+
throw new RemoteError('session/agent-busy', 'prompt rejected', { reason: String(error) })
|
|
383
|
+
}
|
|
384
|
+
return { accepted: true }
|
|
385
|
+
}
|
|
386
|
+
return hasImage ? this.agents.serializeImageAdmission(agent, admit) : admit()
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/** Recover first input acceptance, including claimed or removed messages, from unseen log entries. */
|
|
390
|
+
private hasPromptRequest(session: Session, requestId: SessionRequestId): boolean {
|
|
391
|
+
let receipts = this.promptReceipts.get(session)
|
|
392
|
+
if (receipts === undefined) {
|
|
393
|
+
receipts = { offset: SessionLogOffset(0), messages: new Set(), requests: new Set() }
|
|
394
|
+
this.promptReceipts.set(session, receipts)
|
|
395
|
+
}
|
|
396
|
+
if (receipts.offset !== session.seq) {
|
|
397
|
+
// oxlint-disable-next-line typescript/no-deprecated -- Existing prompt retry history read, retained for acceptance recovery.
|
|
398
|
+
for (const event of session.snapshotEvents(receipts.offset)) {
|
|
399
|
+
if (event.type !== 'agent/inbox/spliced' && event.type !== 'user/message') continue
|
|
400
|
+
const messages = event.type === 'agent/inbox/spliced' ? event.data.inserted : [event.data]
|
|
401
|
+
for (const message of messages) {
|
|
402
|
+
if (receipts.messages.has(message.id)) continue
|
|
403
|
+
receipts.messages.add(message.id)
|
|
404
|
+
// A copied input is not a new request in the child, even if later reinserted there.
|
|
405
|
+
if (event.seq < session.inheritedEventCount) continue
|
|
406
|
+
const source = message.source
|
|
407
|
+
if ((source.kind === 'user' || source.kind === 'retry') && 'rpcId' in source) receipts.requests.add(source.rpcId)
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
receipts.offset = session.seq
|
|
411
|
+
}
|
|
412
|
+
return receipts.requests.has(requestId)
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
private async requireModel(selection: Pick<AgentModelSelection, 'provider' | 'model'>): Promise<void> {
|
|
416
|
+
if (!await modelAvailable(this.ctx, selection)) {
|
|
417
|
+
throw new RemoteError('session/model-unavailable', 'Select an available model before sending a message.',
|
|
418
|
+
{ provider: selection.provider, model: selection.model })
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* Read one durable image using the supplied reference without consulting Session history.
|
|
424
|
+
* @param request - image reference and gateway permission scope; Session existence is not checked.
|
|
425
|
+
* @returns the durable attachment reference and base64-encoded bytes.
|
|
426
|
+
*/
|
|
427
|
+
async attachment(request: SessionAttachmentRequest): Promise<SessionAttachmentValue> {
|
|
428
|
+
try {
|
|
429
|
+
const stored = await this.ctx.attachments.readImage(request.attachment)
|
|
430
|
+
return {
|
|
431
|
+
attachment: stored.ref,
|
|
432
|
+
data: Buffer.from(stored.data).toString('base64'),
|
|
433
|
+
}
|
|
434
|
+
} catch (error) {
|
|
435
|
+
if (error instanceof AttachmentError) {
|
|
436
|
+
throw new RemoteError('session/attachment-invalid', error.message, { reason: error.code })
|
|
437
|
+
}
|
|
438
|
+
throw new RemoteError('gateway/internal', 'Unable to read image attachment.', {})
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/**
|
|
443
|
+
* Mutate one pending Inbox occurrence, restoring an ordinary cold Agent when needed.
|
|
444
|
+
* @param request - Session, queue item, and requested mutation.
|
|
445
|
+
* @returns acknowledgement that the queue mutation was applied.
|
|
446
|
+
*/
|
|
447
|
+
async updateQueue(request: SessionUpdateQueueRequest): Promise<SessionUpdateQueueValue> {
|
|
448
|
+
if (request.action.kind === 'edit') {
|
|
449
|
+
// oxlint-disable-next-line typescript/no-unnecessary-condition -- Remote callers can submit untyped JSON.
|
|
450
|
+
if (request.action.content.some(block => block.type !== 'text')) {
|
|
451
|
+
throw new RemoteError(
|
|
452
|
+
'session/attachment-invalid',
|
|
453
|
+
'queue edits accept text content only',
|
|
454
|
+
{ reason: 'QUEUE_EDIT_NON_TEXT' },
|
|
455
|
+
)
|
|
456
|
+
}
|
|
457
|
+
if (!hasPromptContent(request.action.content)) {
|
|
458
|
+
throw new RemoteError(
|
|
459
|
+
'gateway/bad-request',
|
|
460
|
+
'queue edit content must include non-whitespace text',
|
|
461
|
+
{},
|
|
462
|
+
)
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
let agent = this.ctx.agents.get(request.sessionId)
|
|
466
|
+
if (agent === undefined) {
|
|
467
|
+
const found = await this.agents.resolveAgent(request.sessionId)
|
|
468
|
+
if ('error' in found) {
|
|
469
|
+
if (found.error.code !== 'session/not-found') throw found.error
|
|
470
|
+
throw new RemoteError('session/queue-item-not-found', 'queued item is no longer pending', { itemId: request.itemId })
|
|
471
|
+
}
|
|
472
|
+
agent = found.agent
|
|
473
|
+
}
|
|
474
|
+
if (hasApiSessionSubagentOwner(agent.session)) {
|
|
475
|
+
const identity = this.ctx.sessionProjections
|
|
476
|
+
.snapshot(agent.session, ['subagent'])
|
|
477
|
+
.values.subagent
|
|
478
|
+
if (identity?.mode !== 'continuable'
|
|
479
|
+
|| !agent.session.isOwnSeq(identity.seq)) {
|
|
480
|
+
throw apiSessionSubagentOwnershipError(request.sessionId)
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
const nextTurn = agent.inbox.nextTurn.find(message => message.id === request.itemId)
|
|
484
|
+
const nextStep = agent.inbox.nextStep.find(message => message.id === request.itemId)
|
|
485
|
+
const located = nextTurn === undefined
|
|
486
|
+
? nextStep === undefined ? undefined : { target: 'next-step' as const, message: nextStep }
|
|
487
|
+
: { target: 'next-turn' as const, message: nextTurn }
|
|
488
|
+
if (located === undefined) {
|
|
489
|
+
throw new RemoteError('session/queue-item-not-found', 'queued item is no longer pending', { itemId: request.itemId })
|
|
490
|
+
}
|
|
491
|
+
const { target, message } = located
|
|
492
|
+
if (request.action.kind === 'steer' && (target !== 'next-turn' || agent.status !== 'running')) {
|
|
493
|
+
throw new RemoteError('session/steer-unavailable', 'current turn no longer accepts steering', { itemId: request.itemId })
|
|
494
|
+
}
|
|
495
|
+
switch (request.action.kind) {
|
|
496
|
+
case 'edit':
|
|
497
|
+
agent.inbox.replace(request.itemId, freezeMessage<UserMessage>({
|
|
498
|
+
...message,
|
|
499
|
+
content: [...request.action.content],
|
|
500
|
+
}))
|
|
501
|
+
break
|
|
502
|
+
case 'remove': {
|
|
503
|
+
agent.inbox.remove(request.itemId)
|
|
504
|
+
const source = message.source
|
|
505
|
+
if (source.kind === 'user' && 'rpcId' in source) {
|
|
506
|
+
this.ctx.fileUploads.retirePrompt(agent, source.rpcId)
|
|
507
|
+
}
|
|
508
|
+
break
|
|
509
|
+
}
|
|
510
|
+
case 'steer':
|
|
511
|
+
agent.inbox.remove(request.itemId)
|
|
512
|
+
agent.steer(message)
|
|
513
|
+
break
|
|
514
|
+
/* v8 ignore next 2 -- closed-union exhaustiveness guard */
|
|
515
|
+
default:
|
|
516
|
+
assertNever(request.action, 'queue action')
|
|
517
|
+
}
|
|
518
|
+
return { accepted: true }
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/**
|
|
522
|
+
* Cancel one live ordinary Agent while retaining pending inbox work.
|
|
523
|
+
* @param request - Session whose active Agent turn is cancelled.
|
|
524
|
+
* @returns acknowledgement that cancellation was requested.
|
|
525
|
+
*/
|
|
526
|
+
cancel(request: SessionCancelRequest): SessionCancelValue {
|
|
527
|
+
const agent = this.ctx.agents.get(request.sessionId)
|
|
528
|
+
if (agent === undefined) {
|
|
529
|
+
throw new RemoteError(
|
|
530
|
+
'session/not-found',
|
|
531
|
+
`session "${request.sessionId}" not found (not attached)`,
|
|
532
|
+
{ sessionId: request.sessionId },
|
|
533
|
+
)
|
|
534
|
+
}
|
|
535
|
+
if (hasApiSessionSubagentOwner(agent.session)) {
|
|
536
|
+
throw apiSessionSubagentOwnershipError(request.sessionId)
|
|
537
|
+
}
|
|
538
|
+
agent.cancel({ kind: 'user' }, { keepInbox: true })
|
|
539
|
+
return { accepted: true }
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
private async resolveAgent(sessionId: SessionId): Promise<Agent> {
|
|
543
|
+
const found = await this.agents.resolveAgent(sessionId)
|
|
544
|
+
if ('error' in found) throw found.error
|
|
545
|
+
return found.agent
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
private rejectCreation(error: unknown): never {
|
|
549
|
+
if (remoteErrorOf(error) !== undefined) throw error
|
|
550
|
+
if (error instanceof ApiSessionPresetConflict) {
|
|
551
|
+
throw new RemoteError('agent-preset/conflict', error.message, {
|
|
552
|
+
sessionId: error.sessionId,
|
|
553
|
+
requestedPreset: error.requestedPreset,
|
|
554
|
+
})
|
|
555
|
+
}
|
|
556
|
+
if (error instanceof ApiSessionCwdConflict) {
|
|
557
|
+
throw new RemoteError('session/conflict', error.message, {
|
|
558
|
+
sessionId: error.sessionId,
|
|
559
|
+
requestedCwd: error.requestedCwd,
|
|
560
|
+
...(error.existingCwd === undefined ? {} : { existingCwd: error.existingCwd }),
|
|
561
|
+
})
|
|
562
|
+
}
|
|
563
|
+
if (error instanceof ApiSessionSubagentOwnership) {
|
|
564
|
+
throw apiSessionSubagentOwnershipError(error.sessionId)
|
|
565
|
+
}
|
|
566
|
+
throw new RemoteError('gateway/internal', `failed to create session: ${String(error)}`, {})
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
private async forkWorkspace(source: SessionHeader): Promise<Workspace | undefined> {
|
|
570
|
+
const workspaces = this.ctx.workspaceRegistry.list()
|
|
571
|
+
const direct = workspaces.find(workspace => workspace.sessionIds.includes(source.id))
|
|
572
|
+
if (direct !== undefined || source.origin !== 'subagent') return direct
|
|
573
|
+
const lineage = await this.ctx.sessionQuery.traceSession(source.id)
|
|
574
|
+
for (const ancestor of lineage.ancestors) {
|
|
575
|
+
const workspace = workspaces.find(candidate => candidate.sessionIds.includes(ancestor.header.id))
|
|
576
|
+
if (workspace !== undefined) return workspace
|
|
577
|
+
}
|
|
578
|
+
return undefined
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/** Replace each file part with the file or image its staged receipt names. */
|
|
583
|
+
function resolvePromptFileReceipts(
|
|
584
|
+
content: SessionPromptRequest['content'],
|
|
585
|
+
staged: (receiptId: FileUploadReceiptId) => StagedAttachment | undefined,
|
|
586
|
+
): { readonly content: AttachmentAdmissionPart[]; readonly receiptIds: readonly FileUploadReceiptId[] } {
|
|
587
|
+
const receiptIds = new Set<FileUploadReceiptId>()
|
|
588
|
+
const resolved = content.map((part): AttachmentAdmissionPart => {
|
|
589
|
+
if (part.type !== 'file') return part
|
|
590
|
+
const attachment = staged(part.receiptId)
|
|
591
|
+
if (attachment === undefined) {
|
|
592
|
+
throw new RemoteError(
|
|
593
|
+
'session/attachment-invalid',
|
|
594
|
+
'File was not uploaded for this session.',
|
|
595
|
+
{ reason: 'FILE_NOT_STAGED' },
|
|
596
|
+
)
|
|
597
|
+
}
|
|
598
|
+
receiptIds.add(part.receiptId)
|
|
599
|
+
return attachment
|
|
600
|
+
})
|
|
601
|
+
return { content: resolved, receiptIds: [...receiptIds] }
|
|
602
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/** Constant-size continuation eligibility over the complete durable Session. */
|
|
2
|
+
import type {} from './types.ts'
|
|
3
|
+
import type { ProjectionDefinition } from '@unieai/rabi-session-projection'
|
|
4
|
+
import type { SessionSeq } from '@unieai/rabi-session/types'
|
|
5
|
+
import { brandNumber } from '@unieai/rabi-brand'
|
|
6
|
+
import { z } from 'zod'
|
|
7
|
+
|
|
8
|
+
// Explicit manual requests use a fixed product policy, independent of automatic retry configuration.
|
|
9
|
+
const CONTINUABLE_FAILURES: ReadonlySet<string> = new Set([
|
|
10
|
+
'RATE_LIMIT', 'SERVER', 'TIMEOUT', 'TRANSPORT', 'EMPTY_RESPONSE', 'STREAM_CLOSED',
|
|
11
|
+
])
|
|
12
|
+
|
|
13
|
+
const endingSchema = z.number().int().nonnegative().transform(brandNumber<SessionSeq>).nullable()
|
|
14
|
+
const stateSchema = z.object({
|
|
15
|
+
admitted: z.boolean(),
|
|
16
|
+
failedAttempt: z.boolean(),
|
|
17
|
+
ending: endingSchema,
|
|
18
|
+
})
|
|
19
|
+
|
|
20
|
+
/** Recoverable manual-continuation facts over admitted user input and empty retry messages. */
|
|
21
|
+
export type ContinuationState = z.infer<typeof stateSchema>
|
|
22
|
+
|
|
23
|
+
const EMPTY: ContinuationState = { admitted: false, failedAttempt: false, ending: null }
|
|
24
|
+
|
|
25
|
+
/** Eligibility requires admitted human work and a failed settlement in the last request step. */
|
|
26
|
+
export const continuationProjectionDefinition = {
|
|
27
|
+
key: 'conversationContinuation',
|
|
28
|
+
stateVersion: 4,
|
|
29
|
+
stateSchema,
|
|
30
|
+
init: (): ContinuationState => EMPTY,
|
|
31
|
+
apply: (state, event) => {
|
|
32
|
+
switch (event.type) {
|
|
33
|
+
case 'turn/start':
|
|
34
|
+
return EMPTY
|
|
35
|
+
case 'step/start':
|
|
36
|
+
case 'assistant/message':
|
|
37
|
+
return state.failedAttempt ? { ...state, failedAttempt: false } : state
|
|
38
|
+
case 'user/message':
|
|
39
|
+
return !state.admitted && event.surfaceOp === 'append'
|
|
40
|
+
&& ((event.data.source.kind === 'user' && event.data.content.length > 0)
|
|
41
|
+
|| (event.data.source.kind === 'retry' && event.data.content.length === 0))
|
|
42
|
+
? { ...state, admitted: true } : state
|
|
43
|
+
case 'assistant/attempt':
|
|
44
|
+
return state.failedAttempt ? state : { ...state, failedAttempt: true }
|
|
45
|
+
case 'turn/end': {
|
|
46
|
+
const ending = event.data.reason.kind === 'error' && CONTINUABLE_FAILURES.has(event.data.reason.error.code)
|
|
47
|
+
&& state.admitted && state.failedAttempt ? event.seq : null
|
|
48
|
+
return ending === null ? EMPTY : { ...EMPTY, ending }
|
|
49
|
+
}
|
|
50
|
+
default:
|
|
51
|
+
return state
|
|
52
|
+
}
|
|
53
|
+
},
|
|
54
|
+
wire: {
|
|
55
|
+
viewSchema: endingSchema,
|
|
56
|
+
view: (state: ContinuationState) => state.ending,
|
|
57
|
+
},
|
|
58
|
+
} satisfies ProjectionDefinition<'conversationContinuation', ContinuationState>
|