Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,7 @@ export type {
SubagentSessionRuntime,
SubagentSessionRuntimeSummary,
SubagentSessionSpawn,
SessionConversationCopy,
TurnRecord,
TurnStateMessage,
TurnStatus,
Expand Down Expand Up @@ -295,6 +296,7 @@ export {
isSubagentSessionParent,
isSubagentSessionRuntime,
isSubagentSessionSpawn,
isSessionConversationCopy,
subagentSessionRuntimeSummary,
isTurnStatus,
decodeStoredMessageForRead,
Expand Down
34 changes: 34 additions & 0 deletions packages/core/src/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,20 @@ export interface SubagentSessionSpawn {
initialRunId: string;
}

/**
* Internal publication state for a Host-owned cross-Session conversation copy.
*
* Preparing copies are not product Sessions yet. The Host publishes them only
* after Messages, Runtime Events, Artifacts, and Task Ledger state are durable.
*/
export interface SessionConversationCopy {
kind: 'branch' | 'revision';
sourceSessionId: string;
sourceTurnId: string;
requestFingerprint: `sha256:${string}`;
state: 'preparing' | 'committed';
}

export type SubagentSessionRuntimeSummary = Omit<
SubagentSessionRuntime,
'systemPrompt' | 'categoryPolicy'
Expand Down Expand Up @@ -200,6 +214,8 @@ export interface SessionHeader {
subagentSpawn?: SubagentSessionSpawn;
/** Immutable host-managed filesystem isolation for this child Session. */
subagentWorkspace?: SubagentWorkspaceBinding;
/** Immutable Host publication identity for a cross-Session conversation copy. */
conversationCopy?: SessionConversationCopy;
/** Stable root id for an edit-and-resend version family. */
revisionRootSessionId?: string;
/** Immediate previous version in the same conversation slot. */
Expand Down Expand Up @@ -334,6 +350,10 @@ const SUBAGENT_SESSION_SPAWN_IDENTITY_SHAPE = defineObjectShape<SubagentSessionS
['schemaVersion', 'requestFingerprint', 'initialTurnId', 'initialRunId'],
[],
);
const SESSION_CONVERSATION_COPY_SHAPE = defineObjectShape<SessionConversationCopy>()(
['kind', 'sourceSessionId', 'sourceTurnId', 'requestFingerprint', 'state'],
[],
);
const SESSION_LINEAGE_ID_MAX_CHARS = 512;
const SESSION_LINEAGE_CONTROL_CHARACTERS = /[\u0000-\u001f\u007f]/;
const SUBAGENT_RUNTIME_NAME_MAX_CHARS = 512;
Expand Down Expand Up @@ -415,6 +435,20 @@ export function isSubagentSessionSpawn(value: unknown): value is SubagentSession
);
}

/** Strict decoder guard for Host-owned conversation-copy publication state. */
export function isSessionConversationCopy(value: unknown): value is SessionConversationCopy {
return (
isRecord(value) &&
hasExactShape(value, SESSION_CONVERSATION_COPY_SHAPE) &&
(value.kind === 'branch' || value.kind === 'revision') &&
isSessionLineageId(value.sourceSessionId) &&
isSessionLineageId(value.sourceTurnId) &&
typeof value.requestFingerprint === 'string' &&
/^sha256:[0-9a-f]{64}$/.test(value.requestFingerprint) &&
(value.state === 'preparing' || value.state === 'committed')
);
}

export function subagentSessionRuntimeSummary(
value: SubagentSessionRuntime,
): SubagentSessionRuntimeSummary {
Expand Down
11 changes: 8 additions & 3 deletions packages/runtime-host/src/__tests__/artifact-coordinator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { openInteractiveArtifactStoreForWrite } from '@maka/storage/artifact-sto
import { resolveStorageRoot, tryAcquireInteractiveRootOwner } from '@maka/storage/root-authority';
import { HostArtifactCoordinator } from '../server/artifact-coordinator.js';
import type { ConnectionContext } from '../server/operation-dispatcher.js';
import { SessionAdmissionGate } from '../server/session-admission-gate.js';

const connectionContext: ConnectionContext = {
hostEpoch: 'host-epoch-1',
Expand Down Expand Up @@ -38,9 +39,13 @@ test('Artifact mutation failure requests Host drain and fails closed', async ()
await rm(metadataPath);
await mkdir(metadataPath);
let drainRequests = 0;
const coordinator = new HostArtifactCoordinator(store, () => {
drainRequests += 1;
});
const coordinator = new HostArtifactCoordinator(
store,
() => {
drainRequests += 1;
},
new SessionAdmissionGate(),
);

assert.deepEqual(
await coordinator.handlers['artifact.delete'](
Expand Down
2 changes: 2 additions & 0 deletions packages/runtime-host/src/__tests__/protocol.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,13 @@ describe('Runtime Host bootstrap protocol', () => {
'queue.retract',
'runtime.policy.mutate',
'runtime.policy.query',
'session.branch.create',
'session.catalog.query',
'session.configuration.update',
'session.create',
'session.metadata.update',
'session.read_marker.set',
'session.revision.create',
'skill.catalog.mutate',
'skill.catalog.preview-update',
'skill.catalog.query',
Expand Down
29 changes: 29 additions & 0 deletions packages/runtime-host/src/__tests__/session-admission-gate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,35 @@ test('does not serialize operations for different Sessions', async () => {
await first;
});

test('serializes overlapping multi-Session admissions without lock-order deadlocks', async () => {
const gate = new SessionAdmissionGate();
const entered = deferred();
const release = deferred();
const order: string[] = [];

const first = gate.runMany(['second', 'first'], async (lease) => {
order.push('first:start');
assert.equal(await gate.runAdmitted('first', lease, () => 'first-owned'), 'first-owned');
assert.equal(await gate.runAdmitted('second', lease, () => 'second-owned'), 'second-owned');
entered.resolve();
await release.promise;
order.push('first:end');
});
await entered.promise;
const second = gate.runMany(['first', 'second'], () => {
order.push('second');
});
const independent = gate.run('third', () => {
order.push('third');
});

await independent;
assert.deepEqual(order, ['first:start', 'third']);
release.resolve();
await Promise.all([first, second]);
assert.deepEqual(order, ['first:start', 'third', 'first:end', 'second']);
});

test('keeps the admission open until admitted child work settles', async () => {
const gate = new SessionAdmissionGate();
const childEntered = deferred();
Expand Down
139 changes: 139 additions & 0 deletions packages/runtime-host/src/__tests__/session-revision-protocol.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import assert from 'node:assert/strict';
import { describe, test } from 'node:test';
import {
decodeClientFrame,
decodeHostFrame,
HOST_OPERATION_SPECS,
RuntimeHostProtocolError,
type SessionCatalogProjection,
} from '../protocol/index.js';

describe('Session revision protocol', () => {
test('declares exact ready-only branch and revision commands', () => {
for (const operation of ['session.branch.create', 'session.revision.create'] as const) {
assert.equal(HOST_OPERATION_SPECS[operation].mode, 'command');
assert.equal(HOST_OPERATION_SPECS[operation].availability, 'ready');
assert.deepEqual(
decodeClientFrame({
requestId: 'request-1',
operation,
input: {
sourceSessionId: 'source-session',
targetSessionId: 'target-session',
sourceTurnId: 'turn-1',
expectedSourceRevision: 3,
},
}),
{
requestId: 'request-1',
operation,
input: {
sourceSessionId: 'source-session',
targetSessionId: 'target-session',
sourceTurnId: 'turn-1',
expectedSourceRevision: 3,
},
},
);
}
});

test('rejects aliasing, unknown fields, and mismatched response identities', () => {
assert.throws(
() =>
decodeClientFrame({
requestId: 'request-1',
operation: 'session.branch.create',
input: {
sourceSessionId: 'same-session',
targetSessionId: 'same-session',
sourceTurnId: 'turn-1',
expectedSourceRevision: 1,
},
}),
isInvalidFrame,
);
assert.throws(
() =>
decodeClientFrame({
requestId: 'request-1',
operation: 'session.revision.create',
input: {
sourceSessionId: 'source-session',
targetSessionId: 'target-session',
sourceTurnId: 'turn-1',
expectedSourceRevision: 1,
ignored: true,
},
}),
isInvalidFrame,
);
const input = {
sourceSessionId: 'source-session',
targetSessionId: 'target-session',
sourceTurnId: 'turn-1',
expectedSourceRevision: 1,
};
assert.throws(
() =>
HOST_OPERATION_SPECS['session.branch.create'].assertOutputForInput?.(input, {
kind: 'committed',
session: sessionProjection('wrong-target'),
}),
isInvalidFrame,
);
});

test('preserves optimistic source revision conflicts on the wire', () => {
assert.deepEqual(
decodeHostFrame({
requestId: 'request-1',
operation: 'session.revision.create',
ok: true,
result: {
kind: 'source_revision_conflict',
expectedRevision: 4,
actualRevision: 5,
},
}),
{
requestId: 'request-1',
operation: 'session.revision.create',
ok: true,
result: {
kind: 'source_revision_conflict',
expectedRevision: 4,
actualRevision: 5,
},
},
);
});
});

function sessionProjection(id: string): SessionCatalogProjection {
return {
id,
revision: 1,
cwd: '/workspace',
createdAt: 1,
lastUsedAt: 1,
name: 'Session',
isFlagged: false,
isArchived: false,
labels: [],
labelsTruncated: false,
hasUnread: false,
status: 'active',
backend: 'fake',
llmConnectionSlug: 'fake',
connectionLocked: false,
model: 'fake-model',
permissionMode: 'ask',
collaborationMode: 'agent',
orchestrationMode: 'default',
};
}

function isInvalidFrame(error: unknown): boolean {
return error instanceof RuntimeHostProtocolError && error.code === 'invalid_frame';
}
Loading
Loading