# Hand a file from one agent to another

> Two processes that share no disk pass a file: one uploads it with a description, the other finds it by meaning or by key and checks the sha256.

## The problem

One agent finishes its work and has a file. Another agent, started later on another machine, needs that file. They share no disk, and you do not want to invent a bucket layout or pass an id through a queue only to say where the file is.

At the end of this guide you have one TypeScript file, `handoff.ts`, that plays both agents. The producer uploads two files to [Artefaktum](https://artefaktum.dev) with a title, a description and tags. The consumer is a separate process that is given no id and no path. It finds the file it needs in two ways, by meaning and by an agreed key, downloads it with the sha256 checked, and reads it. The output shown is from our runs against production on 15 November 2026.

## What you need

Node 22.18 or newer, which runs a `.ts` file directly, and an API key from the [console](/console/). The program uses the [TypeScript SDK](/docs/typescript/), pinned to the version it was run with:

```sh
mkdir hand-off && cd hand-off
npm init -y && npm pkg set type=module
npm install --save-exact artefaktum@0.3.0
export ARTEFAKTUM_API_KEY=ak_...
```

The complete program is the blocks below, in the order they appear. It starts with the imports:

```ts
import { createHash } from "node:crypto";
import { readFile, writeFile } from "node:fs/promises";
import { setTimeout as sleep } from "node:timers/promises";
import { Artefaktum, ArtefaktumError } from "artefaktum";
import type { Artifact } from "artefaktum";
```

## What the two agents agree on

The agents never exchange an artifact id. They agree on two things in advance: a tag that names their pipeline, and an `external_key`, a name of your own choosing that is unique within a project, for the one file whose name is known ahead of time. The tags here are the tags of this guide; yours would name your pipeline or team.

```ts
// What the two agents agree on in advance: a tag for the pipeline, and a key for the one
// file whose name is known ahead of time. The ids are never passed around.
const PIPELINE = "hand-off-a-file";
const TAGS = ["blog-guide", PIPELINE];
const PRICES_KEY = "blog-guide/hand-off-a-file/supplier-prices/2026-w46";

// What the consumer wants, in its own words. No word of it has to be in the title.
const QUESTION = "what do plumbing parts cost from our suppliers this week";
// Semantic search returns the nearest artifacts even when none fits, so the consumer
// takes a hit only at or above this similarity.
const CLOSE_ENOUGH = 0.5;
// How long the consumer waits for a file that is not there yet: 10 looks, 2 seconds apart.
const LOOKS = 10;
const PAUSE_MS = 2000;
```

## The producer

The producer is a scraper that ends its run with two files: a price list and its own crawl log. Search matches what describes the artifact, mainly its title, description and tags, never the bytes of the file. So the description is the hand-off: write it for the reader who has never seen the file, and say what is in it and what it is for.

```ts
// The producer's work. A real agent would have scraped these.
const OUTPUTS = [
  {
    filename: "supplier-prices.csv",
    content:
      "sku,supplier,unit_price_eur\n" +
      "CU-15-ELBOW,Nordpipe,1.42\n" +
      "CU-15-TEE,Nordpipe,2.10\n" +
      "PEX-16-50M,Baltic Fittings,38.90\n",
    title: "Supplier price list, week 46",
    description:
      "Unit prices in EUR for copper and PEX fittings from Nordpipe and Baltic Fittings, " +
      "collected on 15 November 2026. One row per SKU: sku, supplier, unit_price_eur. " +
      "Use it to quote installation jobs.",
    external_key: PRICES_KEY,
  },
  {
    filename: "crawl-log.txt",
    content:
      "09:02:11 GET nordpipe.example/catalogue 200\n" +
      "09:02:14 GET balticfittings.example/prices 503, retry in 5 s\n" +
      "09:02:19 GET balticfittings.example/prices 200\n",
    title: "Crawl log, supplier scrape, week 46",
    description:
      "Requests the scraper made on 15 November 2026, with HTTP statuses and retries. " +
      "For debugging the scraper.",
    external_key: "blog-guide/hand-off-a-file/crawl-log/2026-w46",
  },
];
```

`push` takes a path, hashes the file, uploads it and waits until the artifact is `ready`. If the second upload fails, the producer deletes the first: a run that failed should leave the whole result or nothing. If that delete fails too, it is reported on its own line and the run still ends with the error that caused it.

```ts
function sha256(bytes: Uint8Array) {
  return createHash("sha256").update(bytes).digest("hex");
}

async function produce(client: Artefaktum) {
  const uploaded: string[] = [];
  try {
    for (const output of OUTPUTS) {
      // The file exists only in this process's working directory.
      await writeFile(output.filename, output.content);
      // push hashes the file, uploads it and waits until the artifact is ready.
      const artifact = await client.artifacts.push(output.filename, {
        title: output.title,
        // Written for whoever looks for the file later: what is in it and what it is for.
        description: output.description,
        tags: TAGS,
        external_key: output.external_key,
      });
      uploaded.push(artifact.id);
      const digest = sha256(await readFile(output.filename));
      console.log(`uploaded ${output.filename}, sha256 ${digest}`);
    }
  } catch (error) {
    // Half a hand-off is worse than none: take back what this run already uploaded.
    // A delete that fails is reported and does not replace the error that caused it.
    for (const id of uploaded) {
      await client.artifacts.delete(id).catch((failure) => {
        console.error(`could not delete ${id}: ${failure instanceof Error ? failure.message : failure}`);
      });
    }
    throw error;
  }
}
```

The producer prints file names and checksums for you to compare later. It prints no id, and the consumer reads none of its output.

## Find it by meaning

Use search when the consumer knows what it wants but not what the file is called. The question is not the title, and the consumer has never seen the title. Three things in this call come from what we measured.

The mode is `semantic`. In `text` mode every word of the query has to match, and the question found nothing; "supplier price list" found the list. The default mode, `hybrid`, ranked the same way as `semantic` here, but its scores are made from ranks: the two files scored 0.0164 and 0.0161, which tells you nothing about how well either fits.

The search is narrowed to the pipeline's tag. A semantic search returns the nearest artifacts even when none of them fits. Without the tag, the second hit in our account was an unrelated latency report at 0.306, ahead of the crawl log.

The consumer takes the best hit only above a floor. The price list scored 0.610 in every run of the program and the crawl log 0.266, so the floor is 0.5. Measure the scores on your own files before you choose yours. An agent with a model behind it would read the title and description of each hit and decide for itself.

```ts
async function findByMeaning(client: Artefaktum) {
  const page = await client.artifacts.search(QUESTION, {
    mode: "semantic",
    tags_all: [PIPELINE],
    limit: 3,
  });
  for (const hit of page.items) console.log(`  ${hit.score.toFixed(3)}  ${hit.artifact.title}`);
  const best = page.items[0];
  return best && best.score >= CLOSE_ENOUGH ? best.artifact : undefined;
}
```

## Find it by key

Use the key when both sides agreed on the name in advance: this week's price list always lives under the same key, and there is nothing to rank. A key also resolves to an artifact that is not usable yet. Right after a delete we got one back with the status `deleting`, so the consumer checks for `ready`.

```ts
async function findByKey(client: Artefaktum) {
  try {
    const artifact = await client.artifacts.getByExternalKey(PRICES_KEY);
    // A key also resolves to an artifact that is still uploading or being deleted.
    return artifact.status === "ready" ? artifact : undefined;
  } catch (error) {
    if (error instanceof ArtefaktumError && error.code === "artifact_not_found") return undefined;
    throw error;
  }
}
```

When you need no check of your own, `pullByKey(key, dest)` finds and downloads in one call.

## Wait, but not forever

A consumer can start before the producer is done. There is also a second, shorter gap: an artifact is `ready` when its bytes are verified, and it becomes searchable by meaning a moment later, when its description has been embedded. The artifact reports this as `semantic_ready`.

We tried to catch that gap and never saw a search miss a file whose upload had returned. In three timed uploads `push` came back with `semantic_ready` already true, and a search sent within a millisecond found the file by meaning and by words; the answers took 0.27 to 0.40 seconds. In one other upload the flag was false when `push` returned and true on our next sample, under six seconds later, and the semantic search we sent in between already found the file. The bounded wait below is there for the consumer that starts early, and because [the REST reference](/docs/rest/) describes the lag, not because we saw a miss:

```ts
async function waitFor(find: () => Promise<Artifact | undefined>) {
  for (let look = 1; look <= LOOKS; look++) {
    const artifact = await find();
    if (artifact) return artifact;
    console.log(`not there yet (look ${look} of ${LOOKS})`);
    if (look < LOOKS) await sleep(PAUSE_MS);
  }
  throw new Error(`the price list did not show up in ${LOOKS} looks`);
}
```

## Download and verify

`pull` streams the file to disk and compares its sha256 with the one the server recorded at upload. The consumer hashes the file once more only to show you the two values.

```ts
async function consume(client: Artefaktum, find: () => Promise<Artifact | undefined>) {
  const artifact = await waitFor(find);
  console.log(`found "${artifact.title}" (${artifact.id})`);

  // pull streams the file to disk and compares its sha256 with the one the server
  // recorded at upload. On a mismatch it throws IntegrityError and leaves no file.
  const path = await client.artifacts.pull(artifact.id, "inbox/");
  const bytes = await readFile(path);
  console.log(`downloaded ${path}, ${bytes.length} bytes`);
  console.log(`sha256 ${sha256(bytes)}`);
  console.log(`server ${artifact.latest_version?.sha256}`);

  // Use it: the consumer now has an ordinary local file.
  const rows = bytes.toString().trim().split("\n").slice(1);
  const [sku, supplier, price] = rows[0].split(",");
  console.log(`${rows.length} prices; the first: ${sku} from ${supplier} at ${price} EUR`);
}
```

## Clean up, and the last lines

`delete` is accepted at once and finishes in the background. For a few seconds (under two in our probe) the artifact is listed as `deleting` and still holds its key, so `cleanup` waits until the list is empty. After that a new run can use the same keys. It deletes every artifact in the project that carries the pipeline's tag, so give that tag to nothing you want to keep.

```ts
async function cleanup(client: Artefaktum) {
  // delete is accepted at once and finishes in the background. Until then the artifact
  // is listed as "deleting" and still holds its key, so wait until the list is empty.
  for (let look = 1; look <= LOOKS; look++) {
    const page = await client.artifacts.list({ tag: PIPELINE });
    if (page.items.length === 0) return console.log("nothing left");
    for (const artifact of page.items) {
      if (artifact.status === "deleting") continue;
      await client.artifacts.delete(artifact.id);
      console.log(`deleted "${artifact.title}"`);
    }
    await sleep(PAUSE_MS);
  }
  throw new Error("the artifacts are still being deleted; run cleanup again");
}
```

The first argument picks the role. `new Artefaktum()` reads the key from the environment.

```ts
const steps: Record<string, (client: Artefaktum) => Promise<void>> = {
  produce,
  consume: (client) => consume(client, () => findByMeaning(client)),
  "consume-by-key": (client) => consume(client, () => findByKey(client)),
  cleanup,
};

const step = steps[process.argv[2]];
if (!step || !process.env.ARTEFAKTUM_API_KEY) {
  console.error(`usage: ARTEFAKTUM_API_KEY=ak_... node handoff.ts ${Object.keys(steps).join(" | ")}`);
  process.exit(2);
}
try {
  await step(new Artefaktum()); // reads ARTEFAKTUM_API_KEY; project "default"
} catch (error) {
  console.error(`failed: ${error instanceof Error ? error.message : error}`);
  process.exit(1);
}
```

## Run it

Give each agent a folder of its own and start them one after the other:

```sh
mkdir agent-a agent-b
(cd agent-a && node ../handoff.ts produce)
(cd agent-b && node ../handoff.ts consume)
(cd agent-b && node ../handoff.ts consume-by-key)
node handoff.ts cleanup
```

The producer, in `agent-a`:

```text
uploaded supplier-prices.csv, sha256 77691bf02fbdb967d892c28c868b0dce81e0b9e269522c816140fd7087653d66
uploaded crawl-log.txt, sha256 33735a5460b1bd6c73d02b07a0e6365650b34d07e55654b5cec21ed7db4ab0c4
```

The consumer, in `agent-b`, by meaning:

```text
  0.610  Supplier price list, week 46
  0.266  Crawl log, supplier scrape, week 46
found "Supplier price list, week 46" (01a1e086-…)
downloaded inbox/supplier-prices.csv, 111 bytes
sha256 77691bf02fbdb967d892c28c868b0dce81e0b9e269522c816140fd7087653d66
server 77691bf02fbdb967d892c28c868b0dce81e0b9e269522c816140fd7087653d66
3 prices; the first: CU-15-ELBOW from Nordpipe at 1.42 EUR
```

By key the output is the same without the two score lines. Then the cleanup:

```text
deleted "Crawl log, supplier scrape, week 46"
deleted "Supplier price list, week 46"
nothing left
```

The checksum the consumer computed is the one the producer printed, and `agent-b` holds only `inbox/supplier-prices.csv`. On Node 23.6 each command also prints an `ExperimentalWarning` about type stripping, left out above; Node 24.21 does not.

We also started the consumer five seconds before the producer. It looked four times, then found the list on the fifth look (`…` stands for the download lines, which are as above):

```text
not there yet (look 1 of 10)
not there yet (look 2 of 10)
not there yet (look 3 of 10)
not there yet (look 4 of 10)
  0.610  Supplier price list, week 46
found "Supplier price list, week 46" (01a1e084-…)
…
```

Only the price list is in that result: the producer had not uploaded the crawl log yet. The producer's rollback covers a run that fails, not a consumer that arrives in the middle of one; a consumer that needs both files should look for the one the producer uploads last. With nothing to find, the consumer gives up after ten looks and exits with status 1.

Run `produce` twice without `cleanup` and the second run stops at once, because the key is taken:

```text
failed: external_key 'blog-guide/hand-off-a-file/supplier-prices/2026-w46' already exists
```

If a later run should replace the file, pass `if_exists: "version"` to `push` and it adds a version under the same key.

## Where next

- [The TypeScript SDK](/docs/typescript/): every option of `push`, `search` and `pull`.
- In Python the same calls are `push`, `search`, `get_by_external_key` and `pull` on `client.artifacts`; see [the Python SDK](/docs/python/).
- [Concepts](/docs/): statuses, search modes and external keys.
- No account at all: [pay per request](/blog/pay-per-request-from-python/).
