maka-agent 0.2.0-dev.27.20260910 → 0.2.0-dev.28.20260911
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 +106 -0
- package/dist/cli-core.js +7 -0
- package/dist/runtime-host-run-command.js +15 -7
- package/dist/session-import-command.js +69 -0
- package/native/runtime-host-peer/prebuilds/darwin-arm64/maka_runtime_host_peer.node +0 -0
- package/native/runtime-host-peer/prebuilds/linux-arm64/maka_runtime_host_peer.node +0 -0
- package/native/runtime-host-peer/prebuilds/linux-x64/maka_runtime_host_peer.node +0 -0
- package/native/runtime-host-peer/prebuilds/win32-x64/maka_runtime_host_peer.node +0 -0
- package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
- package/node_modules/@earendil-works/pi-tui/dist/components/editor.js +9 -4
- package/node_modules/@maka/core/dist/diagnostic-log.js +18 -7
- package/node_modules/@maka/core/dist/text-sanitize.js +8 -2
- package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +8 -8
- package/node_modules/@maka/runtime/dist/archive-read-tool.js +3 -1
- package/node_modules/@maka/runtime/dist/bots/bot-test.js +2 -1
- package/node_modules/@maka/runtime/dist/bots/feishu-bridge.js +24 -20
- package/node_modules/@maka/runtime/dist/bots/slack-bridge.js +5 -3
- package/node_modules/@maka/runtime/dist/bots/wechat-bridge.js +87 -29
- package/node_modules/@maka/runtime/dist/bots/wecom-bridge.js +40 -36
- package/node_modules/@maka/runtime/dist/computer-use-tools.js +4 -1
- package/node_modules/@maka/runtime/dist/deep-research-tools.js +11 -5
- package/node_modules/@maka/runtime/dist/edit-replace.js +2 -2
- package/node_modules/@maka/runtime/dist/filesystem-worker/operations.js +5 -6
- package/node_modules/@maka/runtime/dist/memory-extraction-evidence.js +7 -1
- package/node_modules/@maka/runtime/dist/memory-extraction.js +12 -7
- package/node_modules/@maka/runtime/dist/openai-responses-websocket.js +2 -5
- package/node_modules/@maka/runtime/dist/plugin-composition-loader.js +11 -2
- package/node_modules/@maka/runtime/dist/request-customization-fetch.js +14 -7
- package/node_modules/@maka/runtime/dist/session-export.js +1 -0
- package/node_modules/@maka/runtime/dist/session-import.js +100 -0
- package/node_modules/@maka/runtime/dist/session-manager.js +6 -1
- package/node_modules/@maka/runtime/dist/shell-run-manager.js +9 -6
- package/node_modules/@maka/runtime/dist/shell-run-tool-result.js +13 -6
- package/node_modules/@maka/runtime/dist/stream-graph-coordinator.js +43 -10
- package/node_modules/@maka/runtime/dist/stream-graph-handoff.js +6 -1
- package/node_modules/@maka/runtime/dist/subscription-model-fetch.js +1 -4
- package/node_modules/@maka/runtime/dist/system-prompt/workspace-instructions.js +11 -6
- package/node_modules/@maka/runtime/dist/tavily-search.js +8 -2
- package/node_modules/@maka/runtime/dist/text-line-window.js +49 -0
- package/node_modules/@maka/runtime/dist/tool-output.js +35 -12
- package/node_modules/@maka/runtime/dist/unified-diff.js +40 -10
- package/node_modules/@maka/runtime/dist/web-fetch-tool.js +4 -2
- package/node_modules/@maka/runtime/dist/workers/filesystem-worker.js +82 -33
- package/node_modules/@maka/runtime/dist/workspace-executor.js +2 -6
- package/node_modules/@maka/runtime/package.json +2 -1
- package/node_modules/@maka/runtime-host/dist/client/host-handoff-copy.js +6 -6
- package/node_modules/@maka/runtime-host/dist/peer-mesh/node.js +7 -4
- package/node_modules/@maka/runtime-host/dist/protocol/artifact.js +2 -2
- package/node_modules/@maka/runtime-host/dist/protocol/index.js +2 -1
- package/node_modules/@maka/runtime-host/dist/protocol/session-transcript.js +3 -2
- package/node_modules/@maka/runtime-host/dist/protocol/skill-catalog.js +2 -1
- package/node_modules/@maka/runtime-host/dist/server/artifact-coordinator.js +2 -0
- package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +29 -4
- package/node_modules/@maka/runtime-host/dist/server/goal-coordinator.js +6 -1
- package/node_modules/@maka/runtime-host/dist/server/interactive-run-composer.js +35 -4
- package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +24 -8
- package/node_modules/@maka/runtime-host/dist/server/root-admission-owner.js +17 -8
- package/node_modules/@maka/runtime-host/dist/server/runtime-resource-projection.js +3 -9
- package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +20 -21
- package/node_modules/@maka/runtime-host/dist/server/session-transcript-pager.js +24 -2
- package/node_modules/@maka/runtime-host/dist/server/skill-catalog-coordinator.js +18 -2
- package/node_modules/@maka/runtime-host/dist/transport/framed-byte-stream-transport.js +4 -1
- package/node_modules/@maka/runtime-host/dist/transport/local-ipc-framing.js +4 -2
- package/node_modules/@maka/runtime-host/dist/transport/peer-native.js +9 -8
- package/node_modules/@maka/runtime-host/dist/transport/resumable-peer-stream.js +14 -9
- package/node_modules/@maka/storage/dist/context-offload-snapshot.js +19 -4
- package/node_modules/@maka/storage/dist/context-value-mutation-gate.js +59 -0
- package/node_modules/@maka/storage/dist/session-bundle-policy.js +579 -7
- package/node_modules/@maka/storage/dist/session-message-projection.js +8 -4
- package/node_modules/@maka/storage/dist/sqlite-context-offload-store.js +18 -4
- package/node_modules/@maka/storage/dist/stable-storage.js +2 -1
- package/node_modules/@modelcontextprotocol/client/dist/src-D_zzAWoS.mjs +22 -5
- package/node_modules/@modelcontextprotocol/client/dist/src-NAgB4Mp8.cjs +22 -5
- package/node_modules/zod/v4/core/memoizer.cjs +12 -16
- package/node_modules/zod/v4/core/memoizer.js +12 -16
- package/package.json +1 -1
|
@@ -16,16 +16,35 @@
|
|
|
16
16
|
* specific language governing permissions and limitations
|
|
17
17
|
* under the License.
|
|
18
18
|
*/
|
|
19
|
-
import { lstat, mkdir, open, readdir, realpath, rename, rm, writeFile, } from 'node:fs/promises';
|
|
19
|
+
import { copyFile, link, lstat, mkdir, open, readFile, readdir, realpath, rename, rm, unlink, writeFile, } from 'node:fs/promises';
|
|
20
20
|
import { constants } from 'node:fs';
|
|
21
21
|
import { randomUUID } from 'node:crypto';
|
|
22
|
-
import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
22
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
23
23
|
import { DatabaseSync } from 'node:sqlite';
|
|
24
24
|
import { decodeArtifactRecordJsons } from './artifact-metadata-codec.js';
|
|
25
|
-
import { withArtifactWriterLock } from './artifact-writer-lock.js';
|
|
25
|
+
import { withArtifactWriterLock, withLeaseBoundArtifactWriterLock, } from './artifact-writer-lock.js';
|
|
26
|
+
import { syncDirectoryChain } from './stable-storage.js';
|
|
27
|
+
import { prepareArtifactWriterLockAuthorityForLease, } from './root-authority.js';
|
|
28
|
+
/**
|
|
29
|
+
* Holds the Artifact writer lock for the root the caller is authorised over.
|
|
30
|
+
*
|
|
31
|
+
* Without a lease the root is named by a path, and the lock is derived from
|
|
32
|
+
* that path again after the authority was checked. A lease says which root the
|
|
33
|
+
* authority covers, so deriving the lock from the lease keeps the two from
|
|
34
|
+
* drifting: an alias or a replaced directory between the two steps would
|
|
35
|
+
* otherwise bind the operation to one root while the lease names another --
|
|
36
|
+
* including an unmarked one, which takes no lock at all.
|
|
37
|
+
*/
|
|
38
|
+
async function withBundleArtifactWriterLock(stateRoot, lease, operation) {
|
|
39
|
+
if (!lease)
|
|
40
|
+
return withArtifactWriterLock(stateRoot, operation);
|
|
41
|
+
const authority = await prepareArtifactWriterLockAuthorityForLease(lease, 'interactive');
|
|
42
|
+
return withLeaseBoundArtifactWriterLock(authority, () => operation(lease.canonicalPath));
|
|
43
|
+
}
|
|
44
|
+
import { runWithContextValueMutation } from './context-value-mutation-gate.js';
|
|
26
45
|
import { withOfflineContextSnapshot, copyContextSnapshot, validateContextSnapshot, planContextSnapshotFiles, } from './context-offload-snapshot.js';
|
|
27
46
|
import { CONTEXT_OFFLOAD_DATABASE_NAME, CONTEXT_OFFLOAD_VALUES_DIRECTORY_NAME, } from './sqlite-context-offload-store.js';
|
|
28
|
-
import { acquireOperationalStateDatabase, inspectOperationalStateSchema, OPERATIONAL_STATE_DATABASE_NAME, } from './operational-state-store.js';
|
|
47
|
+
import { acquireOperationalStateDatabase, inspectOperationalStateSchema, OPERATIONAL_STATE_DATABASE_NAME, OperationalStateMigrationBlockedError, } from './operational-state-store.js';
|
|
29
48
|
import { TERMINAL_RUNTIME_EVENT_SQL } from './runtime-transcript-query.js';
|
|
30
49
|
import { isSafeStorageId } from './storage-id.js';
|
|
31
50
|
export const SESSION_BUNDLE_STATE_ENTRIES = [
|
|
@@ -148,7 +167,7 @@ export async function planSessionBundleExport(input) {
|
|
|
148
167
|
};
|
|
149
168
|
}
|
|
150
169
|
export async function exportSessionBundleState(input) {
|
|
151
|
-
return withOfflineContextSnapshot(input.stateRoot, (contextLocked) =>
|
|
170
|
+
return withOfflineContextSnapshot(input.stateRoot, (contextLocked) => withBundleArtifactWriterLock(input.stateRoot, input.lease, async (stateRoot) => {
|
|
152
171
|
const destinationRoot = resolve(input.destinationRoot);
|
|
153
172
|
await assertDestinationMissing(destinationRoot);
|
|
154
173
|
const stagingRoot = `${destinationRoot}.${process.pid}.${randomUUID()}.tmp`;
|
|
@@ -187,7 +206,7 @@ export async function exportSessionBundleState(input) {
|
|
|
187
206
|
await rm(stagingRoot, { recursive: true, force: true }).catch(() => { });
|
|
188
207
|
throw error;
|
|
189
208
|
}
|
|
190
|
-
}));
|
|
209
|
+
}), input.lease ? { lease: input.lease } : {});
|
|
191
210
|
}
|
|
192
211
|
/**
|
|
193
212
|
* Take the private copy the whole export is derived from.
|
|
@@ -251,7 +270,15 @@ async function backupOperationalState(stateRoot, destinationPath) {
|
|
|
251
270
|
lease = acquireOperationalStateDatabase(stateRoot, { schemaMigration: 'require_current' });
|
|
252
271
|
}
|
|
253
272
|
catch (error) {
|
|
254
|
-
|
|
273
|
+
// Only a blocked migration means "this build cannot read that schema".
|
|
274
|
+
// A permission, busy or I/O failure is the environment talking, and the
|
|
275
|
+
// operational store preserves it deliberately -- flattening those into a
|
|
276
|
+
// schema verdict tells the caller to upgrade when the real answer is that
|
|
277
|
+
// the file could not be opened.
|
|
278
|
+
if (error instanceof OperationalStateMigrationBlockedError) {
|
|
279
|
+
throw new SessionBundleExportError('schema_unsupported', 'Session bundle source is not at the current schema', { cause: error });
|
|
280
|
+
}
|
|
281
|
+
throw error;
|
|
255
282
|
}
|
|
256
283
|
try {
|
|
257
284
|
await lease.backup(destinationPath);
|
|
@@ -442,6 +469,16 @@ const SESSION_LINK_COLUMNS = [
|
|
|
442
469
|
'child_session_id',
|
|
443
470
|
'root_session_id',
|
|
444
471
|
];
|
|
472
|
+
/**
|
|
473
|
+
* Tables the target writes for itself.
|
|
474
|
+
*
|
|
475
|
+
* `session_metadata` carries triggers that maintain the catalog projection, so
|
|
476
|
+
* inserting the bundle's copy of it and then the Session row makes the trigger
|
|
477
|
+
* collide with what was just inserted. The projection is derived; letting the
|
|
478
|
+
* target derive it is both simpler and the only way it stays correct when the
|
|
479
|
+
* derivation changes.
|
|
480
|
+
*/
|
|
481
|
+
const TRIGGER_MAINTAINED_TABLES = new Set(['session_catalog_projection']);
|
|
445
482
|
const PORTABLE_GLOBAL_TABLES = new Set([
|
|
446
483
|
'operational_schema_migrations',
|
|
447
484
|
'session_metadata_schema',
|
|
@@ -636,3 +673,538 @@ function assertSafeSessionId(sessionId) {
|
|
|
636
673
|
function quoteIdentifier(value) {
|
|
637
674
|
return `"${value.replaceAll('"', '""')}"`;
|
|
638
675
|
}
|
|
676
|
+
export class SessionBundleImportError extends Error {
|
|
677
|
+
code;
|
|
678
|
+
constructor(code, message, options) {
|
|
679
|
+
super(message, options);
|
|
680
|
+
this.code = code;
|
|
681
|
+
this.name = 'SessionBundleImportError';
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
/**
|
|
685
|
+
* Merge a hydrated bundle into a workspace.
|
|
686
|
+
*
|
|
687
|
+
* The mirror of the export, and the asymmetry is the whole design: the export
|
|
688
|
+
* owns a private copy and can DELETE what is not the subtree, while the import
|
|
689
|
+
* writes into a live workspace holding other people's Sessions and can only
|
|
690
|
+
* ADD. What keeps that from needing a table list is that the bundle's database
|
|
691
|
+
* already contains nothing else -- so this copies every table it has, and a
|
|
692
|
+
* table added to the schema later travels in both directions without anyone
|
|
693
|
+
* updating a list.
|
|
694
|
+
*
|
|
695
|
+
* Write order is the safety argument. Artifact bytes land first and the
|
|
696
|
+
* database transaction commits last, so a failure between them leaves files
|
|
697
|
+
* nothing points at -- reclaimable -- rather than rows pointing at files that
|
|
698
|
+
* are not there.
|
|
699
|
+
*/
|
|
700
|
+
export async function importSessionBundleState(input) {
|
|
701
|
+
const bundleStateRoot = await canonicalRoot(input.bundleStateRoot, 'bundle state');
|
|
702
|
+
const bundleDatabasePath = resolveInside(bundleStateRoot, OPERATIONAL_STATE_DATABASE_NAME);
|
|
703
|
+
await assertRegularFile(bundleDatabasePath, OPERATIONAL_STATE_DATABASE_NAME);
|
|
704
|
+
// The authority is decided by what is being written, not by what the target
|
|
705
|
+
// already has. A bundle carrying context needs it even for a fresh workspace
|
|
706
|
+
// with no context store yet -- which is exactly the case that would otherwise
|
|
707
|
+
// run unprotected, and the common one.
|
|
708
|
+
const bundleCarriesContext = await pathExists(resolveInside(bundleStateRoot, CONTEXT_OFFLOAD_DATABASE_NAME));
|
|
709
|
+
return withOfflineContextSnapshot(input.stateRoot, (contextLocked) => withBundleArtifactWriterLock(input.stateRoot, input.lease, async (stateRoot) => {
|
|
710
|
+
const sessionIds = readBundleSessionIds(bundleDatabasePath);
|
|
711
|
+
if (sessionIds.length === 0) {
|
|
712
|
+
throw new SessionBundleImportError('invalid_root', 'Bundle carries no Session');
|
|
713
|
+
}
|
|
714
|
+
// The export refuses to migrate its source because it only reads. An
|
|
715
|
+
// import is a write the user asked for, and the target is often a
|
|
716
|
+
// workspace with no database yet -- moving to a new machine is the whole
|
|
717
|
+
// point -- so this opens the ordinary way and lets it be initialised.
|
|
718
|
+
let lease;
|
|
719
|
+
try {
|
|
720
|
+
lease = acquireOperationalStateDatabase(stateRoot);
|
|
721
|
+
}
|
|
722
|
+
catch (error) {
|
|
723
|
+
// A target this build cannot open is a schema verdict, not an IO one;
|
|
724
|
+
// everything else the operational store raises is the environment.
|
|
725
|
+
if (error instanceof OperationalStateMigrationBlockedError) {
|
|
726
|
+
throw new SessionBundleImportError('schema_unsupported', 'Workspace schema cannot be opened by this build', { cause: error });
|
|
727
|
+
}
|
|
728
|
+
throw error;
|
|
729
|
+
}
|
|
730
|
+
try {
|
|
731
|
+
assertBundleSchemaMatches(lease.database, bundleDatabasePath);
|
|
732
|
+
assertImportableInto(lease.database, sessionIds);
|
|
733
|
+
// Everything the Session will reference lands first; the Session rows
|
|
734
|
+
// are the last thing written. A failure before that leaves artifacts
|
|
735
|
+
// and context nothing points at, which the store reclaims, rather than
|
|
736
|
+
// a Session already visible whose bytes never arrived -- and which a
|
|
737
|
+
// retry could not fix, because the ids are now taken.
|
|
738
|
+
const artifacts = await copyBundleArtifacts(bundleStateRoot, stateRoot);
|
|
739
|
+
try {
|
|
740
|
+
const contextRefs = await mergeBundleContext(bundleStateRoot, stateRoot, contextLocked, sessionIds);
|
|
741
|
+
const inserted = mergeBundleDatabase(lease, bundleDatabasePath);
|
|
742
|
+
return { sessionIds: inserted, artifactFiles: artifacts.copied, contextRefs };
|
|
743
|
+
}
|
|
744
|
+
catch (error) {
|
|
745
|
+
// Take back only what this attempt created. Anything already there
|
|
746
|
+
// belongs to someone else, or to an earlier attempt that the next
|
|
747
|
+
// one will recognise.
|
|
748
|
+
for (const path of artifacts.created)
|
|
749
|
+
await rm(path, { force: true }).catch(() => { });
|
|
750
|
+
throw error;
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
finally {
|
|
754
|
+
lease.close();
|
|
755
|
+
}
|
|
756
|
+
}), {
|
|
757
|
+
requireAuthority: bundleCarriesContext,
|
|
758
|
+
...(input.lease ? { lease: input.lease } : {}),
|
|
759
|
+
});
|
|
760
|
+
}
|
|
761
|
+
/**
|
|
762
|
+
* Refuse a bundle written against a different schema.
|
|
763
|
+
*
|
|
764
|
+
* The merge copies rows with `INSERT ... SELECT *`, which maps by position. A
|
|
765
|
+
* bundle whose tables have a different column ORDER but the same count would
|
|
766
|
+
* be inserted silently transposed -- rows that read as data and are not. The
|
|
767
|
+
* export only ever writes a bundle at its own current schema, so any mismatch
|
|
768
|
+
* here means the two builds disagree, and the honest answer is to say so
|
|
769
|
+
* rather than to guess a mapping.
|
|
770
|
+
*/
|
|
771
|
+
function assertBundleSchemaMatches(target, bundleDatabasePath) {
|
|
772
|
+
const bundle = new DatabaseSync(bundleDatabasePath, { readOnly: true });
|
|
773
|
+
try {
|
|
774
|
+
const bundleVersions = readSchemaRegistry(bundle);
|
|
775
|
+
const targetVersions = readSchemaRegistry(target);
|
|
776
|
+
for (const [scope, version] of Object.entries(bundleVersions)) {
|
|
777
|
+
if (targetVersions[scope] !== version) {
|
|
778
|
+
throw new SessionBundleImportError('schema_unsupported', `Bundle schema ${scope} is ${version}; this workspace is ${targetVersions[scope] ?? 'absent'}`);
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
const bundleUserVersion = readUserVersionPragma(bundle);
|
|
782
|
+
const targetUserVersion = readUserVersionPragma(target);
|
|
783
|
+
if (bundleUserVersion !== targetUserVersion) {
|
|
784
|
+
throw new SessionBundleImportError('schema_unsupported', `Bundle runtime schema is ${bundleUserVersion}; this workspace is ${targetUserVersion}`);
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
finally {
|
|
788
|
+
bundle.close();
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
function readSchemaRegistry(database) {
|
|
792
|
+
const versions = {};
|
|
793
|
+
for (const row of database
|
|
794
|
+
.prepare('SELECT scope, version FROM operational_schema_migrations')
|
|
795
|
+
.all()) {
|
|
796
|
+
if (typeof row.scope === 'string' && typeof row.version === 'number') {
|
|
797
|
+
versions[row.scope] = row.version;
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
return versions;
|
|
801
|
+
}
|
|
802
|
+
function readUserVersionPragma(database) {
|
|
803
|
+
const row = (database.prepare('PRAGMA user_version').get() ?? {});
|
|
804
|
+
return Number(Object.values(row)[0] ?? -1);
|
|
805
|
+
}
|
|
806
|
+
/** The same question the export asks before deleting a table wholesale. */
|
|
807
|
+
function describesASession(target, table) {
|
|
808
|
+
if (PORTABLE_DERIVED_TABLES.has(table))
|
|
809
|
+
return true;
|
|
810
|
+
const columns = new Set(target.prepare(`PRAGMA bundle.table_info(${quoteIdentifier(table)})`).all()
|
|
811
|
+
.map((column) => column.name)
|
|
812
|
+
.filter((name) => typeof name === 'string'));
|
|
813
|
+
if (columns.has(SESSION_ROW_OWNER_COLUMN))
|
|
814
|
+
return true;
|
|
815
|
+
return SESSION_LINK_COLUMNS.some((column) => columns.has(column));
|
|
816
|
+
}
|
|
817
|
+
function readBundleSessionIds(bundleDatabasePath) {
|
|
818
|
+
const database = new DatabaseSync(bundleDatabasePath, { readOnly: true });
|
|
819
|
+
try {
|
|
820
|
+
return database
|
|
821
|
+
.prepare('SELECT session_id FROM session_metadata ORDER BY session_id')
|
|
822
|
+
.all().map((row) => String(row.session_id));
|
|
823
|
+
}
|
|
824
|
+
finally {
|
|
825
|
+
database.close();
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
/**
|
|
829
|
+
* Refuse before writing anything.
|
|
830
|
+
*
|
|
831
|
+
* Session ids are generated, not chosen, so one already present means this
|
|
832
|
+
* Session is already here -- not that two of them collided. Importing over it
|
|
833
|
+
* would merge two histories that share ids and agree about nothing else.
|
|
834
|
+
*/
|
|
835
|
+
function assertImportableInto(target, sessionIds) {
|
|
836
|
+
const existing = target.prepare('SELECT 1 FROM session_metadata WHERE session_id = ?');
|
|
837
|
+
const present = sessionIds.filter((sessionId) => existing.get(sessionId) !== undefined);
|
|
838
|
+
if (present.length > 0) {
|
|
839
|
+
throw new SessionBundleImportError('session_exists', `Session already present in this workspace: ${present.join(', ')}`);
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
/**
|
|
843
|
+
* Stage the bundle's artifact bytes, and be able to take them back.
|
|
844
|
+
*
|
|
845
|
+
* Publishing the Session last stops a broken Session from becoming visible, but
|
|
846
|
+
* it does not by itself make the import retryable: bytes written before a later
|
|
847
|
+
* failure stay behind, and a second attempt then trips over its own leftovers.
|
|
848
|
+
*
|
|
849
|
+
* Two rules make a retry work without overwriting anything. A destination that
|
|
850
|
+
* is byte-identical to what the bundle carries is this import's own leftover,
|
|
851
|
+
* or the same content by another route, and is accepted. A destination holding
|
|
852
|
+
* something else is a real conflict. Files this attempt actually created are
|
|
853
|
+
* remembered, so a failure can remove exactly those and nothing else.
|
|
854
|
+
*/
|
|
855
|
+
async function copyBundleArtifacts(bundleStateRoot, stateRoot) {
|
|
856
|
+
const source = resolveInside(bundleStateRoot, 'artifacts');
|
|
857
|
+
const created = [];
|
|
858
|
+
if (!(await pathExists(source)))
|
|
859
|
+
return { copied: 0, created };
|
|
860
|
+
let copied = 0;
|
|
861
|
+
const walk = async (relative) => {
|
|
862
|
+
const absolute = relative ? resolveInside(source, relative) : source;
|
|
863
|
+
for (const entry of await readdir(absolute, { withFileTypes: true })) {
|
|
864
|
+
const next = relative ? `${relative}/${entry.name}` : entry.name;
|
|
865
|
+
if (entry.isDirectory()) {
|
|
866
|
+
await walk(next);
|
|
867
|
+
continue;
|
|
868
|
+
}
|
|
869
|
+
if (!entry.isFile()) {
|
|
870
|
+
throw new SessionBundleImportError('io_failed', `Bundle artifact is not a regular file: ${next}`);
|
|
871
|
+
}
|
|
872
|
+
const from = resolveInside(source, next);
|
|
873
|
+
const destination = resolveInside(resolveInside(stateRoot, 'artifacts'), next);
|
|
874
|
+
await mkdir(dirname(destination), { recursive: true });
|
|
875
|
+
try {
|
|
876
|
+
await copyFile(from, destination, constants.COPYFILE_EXCL);
|
|
877
|
+
created.push(destination);
|
|
878
|
+
}
|
|
879
|
+
catch (error) {
|
|
880
|
+
if (error.code !== 'EEXIST')
|
|
881
|
+
throw error;
|
|
882
|
+
if (!(await sameFileContent(from, destination))) {
|
|
883
|
+
throw new SessionBundleImportError('conflict', `Artifact already present: ${next}`);
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
copied += 1;
|
|
887
|
+
}
|
|
888
|
+
};
|
|
889
|
+
await walk('');
|
|
890
|
+
return { copied, created };
|
|
891
|
+
}
|
|
892
|
+
async function sameFileContent(left, right) {
|
|
893
|
+
const [a, b] = await Promise.all([readFile(left), readFile(right)]);
|
|
894
|
+
return a.equals(b);
|
|
895
|
+
}
|
|
896
|
+
/**
|
|
897
|
+
* Copy every table the bundle has, in one transaction.
|
|
898
|
+
*
|
|
899
|
+
* No allow-list: the bundle's database was already filtered down to its own
|
|
900
|
+
* Sessions, so "everything it has" is exactly what belongs. Only the tables
|
|
901
|
+
* describing the WORKSPACE rather than a Session are skipped -- the target has
|
|
902
|
+
* its own, and they are not the bundle's to bring.
|
|
903
|
+
*/
|
|
904
|
+
function mergeBundleDatabase(lease, bundleDatabasePath) {
|
|
905
|
+
const target = lease.database;
|
|
906
|
+
// Read-only, so a bundle is never written by the act of reading it -- and so
|
|
907
|
+
// a hydrated staging tree cannot pick up a journal beside it.
|
|
908
|
+
const uri = `file:${encodeURI(bundleDatabasePath)}?mode=ro`;
|
|
909
|
+
target.exec(`ATTACH DATABASE '${uri.replaceAll("'", "''")}' AS bundle`);
|
|
910
|
+
try {
|
|
911
|
+
// The lease owns a shared, reference-counted connection with its own
|
|
912
|
+
// transaction depth. Driving BEGIN/COMMIT directly would step around that,
|
|
913
|
+
// and the foreign-key pragma it needs must be put back: leaving it off
|
|
914
|
+
// would silently disarm constraint checking for every later user of this
|
|
915
|
+
// connection.
|
|
916
|
+
const restoreForeignKeys = Number(Object.values((target.prepare('PRAGMA foreign_keys').get() ?? {}))[0] ?? 0) === 1;
|
|
917
|
+
target.exec('PRAGMA foreign_keys = OFF');
|
|
918
|
+
try {
|
|
919
|
+
return lease.transaction('write', () => mergeAttachedBundle(target));
|
|
920
|
+
}
|
|
921
|
+
finally {
|
|
922
|
+
if (restoreForeignKeys)
|
|
923
|
+
target.exec('PRAGMA foreign_keys = ON');
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
finally {
|
|
927
|
+
target.exec('DETACH DATABASE bundle');
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
function mergeAttachedBundle(target) {
|
|
931
|
+
{
|
|
932
|
+
{
|
|
933
|
+
const tables = target
|
|
934
|
+
.prepare("SELECT name FROM bundle.sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name")
|
|
935
|
+
.all();
|
|
936
|
+
for (const row of tables) {
|
|
937
|
+
const name = row.name;
|
|
938
|
+
if (typeof name !== 'string' ||
|
|
939
|
+
PORTABLE_GLOBAL_TABLES.has(name) ||
|
|
940
|
+
TRIGGER_MAINTAINED_TABLES.has(name)) {
|
|
941
|
+
continue;
|
|
942
|
+
}
|
|
943
|
+
// Mirror the export's own classification instead of trusting that it
|
|
944
|
+
// ran: a table with no Session column and no referential rule describes
|
|
945
|
+
// the WORKSPACE, and the target has its own. The export empties those,
|
|
946
|
+
// so in practice this inserts nothing -- but an import that depends on
|
|
947
|
+
// the other side having tidied up is one bundle away from writing a
|
|
948
|
+
// workspace singleton into somebody else's workspace.
|
|
949
|
+
if (!describesASession(target, name))
|
|
950
|
+
continue;
|
|
951
|
+
const quoted = quoteIdentifier(name);
|
|
952
|
+
target.exec(`INSERT INTO main.${quoted} SELECT * FROM bundle.${quoted}`);
|
|
953
|
+
}
|
|
954
|
+
const violation = target.prepare('PRAGMA foreign_key_check').get();
|
|
955
|
+
if (violation) {
|
|
956
|
+
throw new SessionBundleImportError('conflict', 'Imported Sessions would leave dangling references');
|
|
957
|
+
}
|
|
958
|
+
return target
|
|
959
|
+
.prepare('SELECT session_id FROM bundle.session_metadata ORDER BY session_id')
|
|
960
|
+
.all().map((entry) => String(entry.session_id));
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
async function pathExists(path) {
|
|
965
|
+
return lstat(path)
|
|
966
|
+
.then(() => true)
|
|
967
|
+
.catch(() => false);
|
|
968
|
+
}
|
|
969
|
+
/**
|
|
970
|
+
* Merge the bundle's offloaded context into the workspace.
|
|
971
|
+
*
|
|
972
|
+
* Without this an imported Session arrives with its read-image references
|
|
973
|
+
* intact and none of the bytes behind them, which is the same hole the export
|
|
974
|
+
* had before it learned to carry the closure.
|
|
975
|
+
*
|
|
976
|
+
* Blobs are content-addressed, so an id already present is the same bytes and
|
|
977
|
+
* the insert is skipped rather than treated as a conflict.
|
|
978
|
+
*/
|
|
979
|
+
async function mergeBundleContext(bundleStateRoot, stateRoot, contextLocked, sessionIds) {
|
|
980
|
+
const bundleContext = resolveInside(bundleStateRoot, CONTEXT_OFFLOAD_DATABASE_NAME);
|
|
981
|
+
if (!(await pathExists(bundleContext)))
|
|
982
|
+
return 0;
|
|
983
|
+
if (!contextLocked) {
|
|
984
|
+
throw new SessionBundleImportError('io_failed', 'Context import requires an offline Storage Root; stop the Runtime Host first');
|
|
985
|
+
}
|
|
986
|
+
// An archive digest authenticates the archive, not the state inside it: it
|
|
987
|
+
// says the bytes arrived as sent, and nothing about whether a row claiming a
|
|
988
|
+
// hash names a file that actually hashes to it. Validated here, against the
|
|
989
|
+
// hydrated copy, before anything is written to the target -- a payload that
|
|
990
|
+
// fails is a bundle nobody can use, and importing it publishes a reference to
|
|
991
|
+
// content that cannot be read back.
|
|
992
|
+
await validateContextSnapshot(bundleStateRoot);
|
|
993
|
+
// Everything below is one turn in the Storage Root's context mutation queue,
|
|
994
|
+
// shared with the Context Store's own publication and collection. Those
|
|
995
|
+
// operations read database state, await, and only then act on files --
|
|
996
|
+
// collection decides a payload is unreferenced, awaits, unlinks it -- so an
|
|
997
|
+
// import that commits a reference inside that await leaves the reference
|
|
998
|
+
// pointing at a file that is about to disappear. The re-check collection does
|
|
999
|
+
// cannot see it, because the check and the unlink straddle the await.
|
|
1000
|
+
return runWithContextValueMutation(stateRoot, async () => {
|
|
1001
|
+
// Managed payloads live at `sha256/<prefix>/<hash>`, so a copy that visited
|
|
1002
|
+
// only immediate children saw one directory, skipped it, and reported a
|
|
1003
|
+
// successful import whose referenced bytes were all absent.
|
|
1004
|
+
const destination = resolveInside(stateRoot, CONTEXT_OFFLOAD_VALUES_DIRECTORY_NAME);
|
|
1005
|
+
await mkdir(destination, { recursive: true, mode: 0o700 });
|
|
1006
|
+
await copyContextValueTree(resolveInside(bundleStateRoot, CONTEXT_OFFLOAD_VALUES_DIRECTORY_NAME), destination, stateRoot);
|
|
1007
|
+
return mergeBundleContextDatabase(bundleContext, stateRoot, sessionIds);
|
|
1008
|
+
});
|
|
1009
|
+
}
|
|
1010
|
+
async function mergeBundleContextDatabase(bundleContext, stateRoot, sessionIds) {
|
|
1011
|
+
const targetContext = resolveInside(stateRoot, CONTEXT_OFFLOAD_DATABASE_NAME);
|
|
1012
|
+
if (!(await pathExists(targetContext))) {
|
|
1013
|
+
await copyFile(bundleContext, targetContext);
|
|
1014
|
+
return countContextRefs(targetContext, sessionIds);
|
|
1015
|
+
}
|
|
1016
|
+
const database = new DatabaseSync(targetContext);
|
|
1017
|
+
try {
|
|
1018
|
+
database.exec(`ATTACH DATABASE '${bundleContext.replaceAll("'", "''")}' AS bundle`);
|
|
1019
|
+
try {
|
|
1020
|
+
database.exec('BEGIN IMMEDIATE');
|
|
1021
|
+
try {
|
|
1022
|
+
database.exec('INSERT OR IGNORE INTO main.context_blobs SELECT * FROM bundle.context_blobs');
|
|
1023
|
+
// A retry re-inserts the same rows. Skipping an identical one is what
|
|
1024
|
+
// makes the second attempt work; skipping a DIFFERENT row that happens
|
|
1025
|
+
// to share an id would hide a real collision, so the two are separated.
|
|
1026
|
+
const colliding = database
|
|
1027
|
+
.prepare(`
|
|
1028
|
+
SELECT b.ref_id FROM bundle.context_refs b
|
|
1029
|
+
JOIN main.context_refs m USING(ref_id)
|
|
1030
|
+
WHERE m.session_id <> b.session_id OR m.blob_id <> b.blob_id
|
|
1031
|
+
`)
|
|
1032
|
+
.all();
|
|
1033
|
+
if (colliding.length > 0) {
|
|
1034
|
+
throw new SessionBundleImportError('conflict', `Context reference already names different content: ${String(colliding[0]?.ref_id)}`);
|
|
1035
|
+
}
|
|
1036
|
+
database.exec('INSERT OR IGNORE INTO main.context_refs SELECT * FROM bundle.context_refs');
|
|
1037
|
+
// A blob the target already held may have been queued for collection
|
|
1038
|
+
// while nothing referenced it. It is referenced again now, and leaving
|
|
1039
|
+
// the candidate behind makes the next collection fail outright --
|
|
1040
|
+
// `Context garbage candidate is still referenced or missing` -- and
|
|
1041
|
+
// keep failing. Ordinary insertion in the Store clears it the same way.
|
|
1042
|
+
database.exec(`
|
|
1043
|
+
DELETE FROM main.context_gc_candidates
|
|
1044
|
+
WHERE blob_id IN (SELECT blob_id FROM main.context_refs)
|
|
1045
|
+
`);
|
|
1046
|
+
// The context store maintains its usage tables explicitly -- no trigger
|
|
1047
|
+
// does it. Inserting blobs and refs without them leaves quotas and the
|
|
1048
|
+
// cleanup consistency checks reading numbers that describe a store that
|
|
1049
|
+
// no longer exists. Recomputed from what is actually there, which is
|
|
1050
|
+
// the same thing the export does when it filters.
|
|
1051
|
+
database.exec(`
|
|
1052
|
+
DELETE FROM context_session_usage;
|
|
1053
|
+
INSERT INTO context_session_usage
|
|
1054
|
+
SELECT r.session_id, count(*), sum(b.size_bytes)
|
|
1055
|
+
FROM context_refs r JOIN context_blobs b USING(blob_id) GROUP BY r.session_id;
|
|
1056
|
+
UPDATE context_store_usage SET
|
|
1057
|
+
blob_count = (SELECT count(*) FROM context_blobs),
|
|
1058
|
+
-- Bytes queued for deletion are still on disk and still charged:
|
|
1059
|
+
-- the store drops a blob row before draining its file and subtracts
|
|
1060
|
+
-- them when the drain completes. Recomputing from live blobs alone
|
|
1061
|
+
-- makes that later subtraction underflow. The export can use the
|
|
1062
|
+
-- simpler sum because it empties the queue on its private copy;
|
|
1063
|
+
-- a live target keeps it.
|
|
1064
|
+
physical_bytes =
|
|
1065
|
+
(SELECT coalesce(sum(size_bytes), 0) FROM context_blobs) +
|
|
1066
|
+
(SELECT coalesce(sum(size_bytes), 0) FROM context_file_deletions)
|
|
1067
|
+
WHERE singleton = 1;
|
|
1068
|
+
`);
|
|
1069
|
+
database.exec('COMMIT');
|
|
1070
|
+
}
|
|
1071
|
+
catch (error) {
|
|
1072
|
+
try {
|
|
1073
|
+
database.exec('ROLLBACK');
|
|
1074
|
+
}
|
|
1075
|
+
catch { }
|
|
1076
|
+
throw error;
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
1079
|
+
finally {
|
|
1080
|
+
database.exec('DETACH DATABASE bundle');
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
finally {
|
|
1084
|
+
database.close();
|
|
1085
|
+
}
|
|
1086
|
+
return countContextRefs(targetContext, sessionIds);
|
|
1087
|
+
}
|
|
1088
|
+
/**
|
|
1089
|
+
* Copy a managed-payload tree, structure and all.
|
|
1090
|
+
*
|
|
1091
|
+
* Content-addressed names mean an existing file is the same file, so an
|
|
1092
|
+
* already-present payload is left alone rather than treated as a conflict.
|
|
1093
|
+
*/
|
|
1094
|
+
async function copyContextValueTree(source, destination, stateRoot) {
|
|
1095
|
+
if (!(await pathExists(source)))
|
|
1096
|
+
return;
|
|
1097
|
+
await assertManagedDestinationDirectory(destination, stateRoot);
|
|
1098
|
+
for (const entry of await readdir(source, { withFileTypes: true })) {
|
|
1099
|
+
const from = resolveInside(source, entry.name);
|
|
1100
|
+
const to = resolveInside(destination, entry.name);
|
|
1101
|
+
if (entry.isDirectory()) {
|
|
1102
|
+
await mkdir(to, { recursive: true, mode: 0o700 });
|
|
1103
|
+
await copyContextValueTree(from, to, stateRoot);
|
|
1104
|
+
continue;
|
|
1105
|
+
}
|
|
1106
|
+
if (!entry.isFile()) {
|
|
1107
|
+
throw new SessionBundleImportError('io_failed', `Bundle context payload is not a regular file: ${entry.name}`);
|
|
1108
|
+
}
|
|
1109
|
+
await publishContextValue(from, to, stateRoot);
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
/**
|
|
1113
|
+
* Refuses a destination directory that does not really live inside the Storage
|
|
1114
|
+
* Root.
|
|
1115
|
+
*
|
|
1116
|
+
* `resolveInside` compares strings, which says nothing about what the path
|
|
1117
|
+
* resolves to: a `context-offload-values` replaced by a symlink passes it and
|
|
1118
|
+
* then receives the payloads somewhere else entirely. The Context Store already
|
|
1119
|
+
* holds this invariant over its own managed directories, and a directory it
|
|
1120
|
+
* would refuse to publish into is not one an import may publish into either.
|
|
1121
|
+
*/
|
|
1122
|
+
async function assertManagedDestinationDirectory(directory, stateRoot) {
|
|
1123
|
+
let entry;
|
|
1124
|
+
let resolved;
|
|
1125
|
+
try {
|
|
1126
|
+
[entry, resolved] = await Promise.all([lstat(directory), realpath(directory)]);
|
|
1127
|
+
}
|
|
1128
|
+
catch (error) {
|
|
1129
|
+
if (error.code === 'ENOTDIR') {
|
|
1130
|
+
throw new SessionBundleImportError('io_failed', `Context payload directory is not a directory: ${directory}`);
|
|
1131
|
+
}
|
|
1132
|
+
throw error;
|
|
1133
|
+
}
|
|
1134
|
+
const fromRoot = relative(stateRoot, resolved);
|
|
1135
|
+
if (!entry.isDirectory() ||
|
|
1136
|
+
entry.isSymbolicLink() ||
|
|
1137
|
+
fromRoot === '..' ||
|
|
1138
|
+
fromRoot.startsWith(`..${sep}`) ||
|
|
1139
|
+
isAbsolute(fromRoot)) {
|
|
1140
|
+
throw new SessionBundleImportError('io_failed', `Context payload directory escapes the Storage Root: ${directory}`);
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
/**
|
|
1144
|
+
* Publishes one payload the way the Context Store publishes its own: the bytes
|
|
1145
|
+
* are assembled under a staging name and become visible at the final path by a
|
|
1146
|
+
* single `link`.
|
|
1147
|
+
*
|
|
1148
|
+
* `copyFile` fills its destination progressively, so the final path is
|
|
1149
|
+
* observable half-written -- measured at 38 distinct intermediate sizes while
|
|
1150
|
+
* copying 64 MiB. Payloads are content-addressed, so a bundle and its target
|
|
1151
|
+
* routinely name the same path, and that path is one another Session may be
|
|
1152
|
+
* reading. It also decides what a retry sees: a copy interrupted midway leaves
|
|
1153
|
+
* a truncated file AT the final path, and the previous `EEXIST`-is-fine rule
|
|
1154
|
+
* accepted it as already present.
|
|
1155
|
+
*
|
|
1156
|
+
* The staging name is the Store's with a different suffix. Two imports cannot
|
|
1157
|
+
* race -- both need the write authority, and it is exclusive -- but an import
|
|
1158
|
+
* and the Store publishing the same blob can, and they must not share a name.
|
|
1159
|
+
*/
|
|
1160
|
+
async function publishContextValue(from, to, stateRoot) {
|
|
1161
|
+
const staging = join(dirname(to), `.${basename(to)}.import.tmp`);
|
|
1162
|
+
await rm(staging, { force: true });
|
|
1163
|
+
try {
|
|
1164
|
+
await copyFile(from, staging, constants.COPYFILE_EXCL);
|
|
1165
|
+
// 'r+' rather than 'r': Windows flushes through the handle and refuses a
|
|
1166
|
+
// read-only one, so a read handle would make this fail only on Windows.
|
|
1167
|
+
const handle = await open(staging, 'r+');
|
|
1168
|
+
try {
|
|
1169
|
+
await handle.sync();
|
|
1170
|
+
}
|
|
1171
|
+
finally {
|
|
1172
|
+
await handle.close();
|
|
1173
|
+
}
|
|
1174
|
+
try {
|
|
1175
|
+
await link(staging, to);
|
|
1176
|
+
// The bytes were synced; the directory entry naming them was not. A crash
|
|
1177
|
+
// here otherwise keeps the committed reference and loses the name, which
|
|
1178
|
+
// reads exactly like a payload that never arrived.
|
|
1179
|
+
await syncDirectoryChain(dirname(to), stateRoot);
|
|
1180
|
+
}
|
|
1181
|
+
catch (error) {
|
|
1182
|
+
if (error.code !== 'EEXIST')
|
|
1183
|
+
throw error;
|
|
1184
|
+
// Reaching the final path now means the payload was already there, not
|
|
1185
|
+
// that this import put it there. Content addressing says it should be
|
|
1186
|
+
// byte-identical; if it is not, the store holds something this bundle
|
|
1187
|
+
// cannot explain and overwriting it would destroy the other Session's
|
|
1188
|
+
// payload.
|
|
1189
|
+
if (!(await sameFileContent(from, to))) {
|
|
1190
|
+
throw new SessionBundleImportError('conflict', `Context payload already names different content: ${basename(to)}`);
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
finally {
|
|
1195
|
+
await unlink(staging).catch(() => { });
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
function countContextRefs(databasePath, sessionIds) {
|
|
1199
|
+
const database = new DatabaseSync(databasePath, { readOnly: true });
|
|
1200
|
+
try {
|
|
1201
|
+
const placeholders = sessionIds.map(() => '?').join(', ');
|
|
1202
|
+
const row = database
|
|
1203
|
+
.prepare(`SELECT COUNT(*) AS count FROM context_refs WHERE session_id IN (${placeholders})`)
|
|
1204
|
+
.get(...sessionIds);
|
|
1205
|
+
return Number(row.count ?? 0);
|
|
1206
|
+
}
|
|
1207
|
+
finally {
|
|
1208
|
+
database.close();
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
@@ -69,10 +69,14 @@ function normalizePreviewText(text) {
|
|
|
69
69
|
return text.replace(/\s+/g, ' ').trim();
|
|
70
70
|
}
|
|
71
71
|
function truncatePreview(text, maxLength = 96) {
|
|
72
|
-
const chars =
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
72
|
+
const chars = [];
|
|
73
|
+
for (const point of text) {
|
|
74
|
+
if (chars.length === maxLength) {
|
|
75
|
+
return `${chars.slice(0, maxLength - 1).join('')}…`;
|
|
76
|
+
}
|
|
77
|
+
chars.push(point);
|
|
78
|
+
}
|
|
79
|
+
return text;
|
|
76
80
|
}
|
|
77
81
|
/** One Turn's summary, folded message by message in transcript order. */
|
|
78
82
|
export function foldTurnContribution(current, turnId, sequence, message) {
|