Pular para o conteúdo
Skillpedia
Código em geral19 mil · #10496

iii-observe

O que ela faz

Mostra como fazer uma função reagir a eventos de outra função, sem alterar a original. Ela é para desenvolvedores que querem adicionar alertas, registros em log ou tarefas de acompanhamento a uma função existente do iii.

Quando usar

  • ✓Quando você quer executar tarefas de acompanhamento depois que outra função tem sucesso ou falha.
  • ✓Quando você quer adicionar alertas ou registros em log a uma função existente sem editá-la.
  • ✓Quando você está migrando código antigo de gatilhos para a abordagem mais nova de observadores.

Link da skill

https://github.com/iii-hq/iii/blob/main/skills/iii-observe/SKILL.md

Copie e cole na sua IA (Claude, ChatGPT ou Cursor) pedindo para seguir as instruções.

Como usar

O jeito mais fácil: copie a mensagem e cole na sua IA. Ela lê a skill e segue as instruções.

Mensagem pronta para colar

Use esta skill para me ajudar: https://github.com/iii-hq/iii/blob/main/skills/iii-observe/SKILL.md Leia o arquivo SKILL.md desse link e siga as instruções dele na minha tarefa.
Quer que a sua IA encontre skills como esta sozinha?Instale o MCP grátis do Skillpedia: uma linha, e ela pesquisa entre 15.000+ skills antes de cada tarefa.Instalar em 1 minuto →

Exemplo do que pedir para a IA

“Me avise sempre que a função orders::validate falhar, sem alterar o código dela.”

5 skills novas por semana. 1 minuto de leitura.

Como funciona

A skill conecta uma função de origem a um alvo por meio de um observador, adicionando filtros se necessário. Cada evento que passa pelos filtros invoca o alvo. O observador aguarda até que o alvo esteja registrado, e a abordagem antiga de gatilhos ainda funciona por enquanto.

Conteúdo técnico (SKILL.md original)

Texto original do autor, em inglês, direto do GitHub.

Observe

Since iii 0.25 every function is observable. iii.observe(source, target, options?) connects a source function to a target function: each event of the source that passes the observer's filters invokes the target. It replaces registerTrigger, and an observe descriptor on registerFunction replaces registerTriggerType. Both old APIs still work in 0.25 (see Migrating from triggers).

Part Fields Notes
source (left side) function_id, namespace?, args?, filters?, on?, capture?, deliver? args only for owner-delivered functions. on (auto only): success (default), error, complete. capture (auto and obs.emit): default ['input', 'output', 'caller'], [] allowed. deliver: envelope (default), input, output
target (right side) a registered function id (or { function_id, namespace }) No inline handler. The observer stays pending until the target is registered
options id?, max_fires?, expires_in_ms?, max_in_flight?, metadata? id defaults to a UUID kept across replays. metadata is the sidecar of every activation

The source namespace resolves like trigger(): the worker's namespace, except engine::* and configuration::*, which resolve in default.

Observe a function

Register the target first, then observe. This alerts on failed charges of 500 or more:

import { registerWorker, type Observed } from "iii-sdk";

const iii = registerWorker(process.env.III_URL ?? "ws://localhost:49134");

iii.registerFunction("alerts::payment-failed", async (event: Observed<{ amount: number }>) => {
  console.log(event.function_id, event.error?.code, event.input?.amount, event.caller?.worker_name);
  return null; // ignored for auto delivery
});

const failures = iii.observe(
  {
    function_id: "payments::charge",
    on: "error",
    filters: { "input.amount": { $gte: 500 } },
    capture: ["input", "error", "caller"],
  },
  "alerts::payment-failed",
  { max_in_flight: 4 },
);
await failures.ready(); // rejects with ObserveRejection (error.code) on error or disposed
// later: await failures.dispose()
iii.register_function("alerts::payment-failed", lambda event: print(event["error"]["code"]))

failures = iii.observe(
    {"function_id": "payments::charge", "on": "error",
     "filters": {"input.amount": {"$gte": 500}}, "capture": ["input", "error", "caller"]},
    "alerts::payment-failed",
    {"max_in_flight": 4},
)
failures.ready()  # blocks; in async code: await failures.ready_async()
use iii_sdk::{Capture, Error, ObserverOptions, Observed, On, RegisterFunction, Source};
use serde_json::{json, Value};

iii.register_function(
    "alerts::payment-failed",
    RegisterFunction::new(|event: Observed<Value>| {
        println!("{} failed: {:?}", event.function_id, event.error);
        Ok::<_, Error>(())
    }),
);
let failures = iii.observe_with(
    Source::function("payments::charge")
        .on(On::Error)
        .filters(json!({ "input.amount": { "$gte": 500 } }))
        .capture([Capture::Input, Capture::Error, Capture::Caller]),
    "alerts::payment-failed",
    ObserverOptions::default().max_in_flight(4),
);
failures.ready().await?;
client.RegisterFunction("alerts::payment-failed", func(ctx context.Context, data json.RawMessage) (any, error) {
	var ev iii.Observed
	if err := json.Unmarshal(data, &ev); err != nil {
		return nil, err
	}
	log.Printf("%s failed: %s", ev.FunctionID, ev.Error.Code)
	return nil, nil
})
failures, err := client.Observe(iii.Source{
	FunctionID: "payments::charge",
	On:         iii.OnError,
	Filters:    iii.Filters{"input.amount": iii.Op{"$gte": 500}},
	Capture:    []iii.Capture{iii.CaptureInput, iii.CaptureError, iii.CaptureCaller},
}, "alerts::payment-failed", iii.ObserverOptions{MaxInFlight: 4})
if err == nil {
	err = failures.Ready(ctx) // *iii.ObserveRejectionError carries the code
}

The browser SDK (iii-browser-sdk) has the same observe API as Node.

What the target receives

  • Envelope (default deliver): { observer_id, activation_id, function_id, namespace, invocation_id, status, input?, output?, error?, caller?, metadata?, started_at_ms, duration_ms }. Only captured fields are present. deliver: 'input' or 'output' sends that value alone.
  • The observer's options.metadata arrives as the handler's metadata argument (Node and browser second argument, Python `met
Perguntas frequentes

A função de origem precisa de alterações?

Não. Um observador se conecta a ela de fora, sem editar o código.

Posso filtrar quais chamadas executam o observador?

Sim. Os filtros decidem quais eventos invocam o alvo.

A abordagem antiga de gatilhos ainda tem suporte?

Sim. Ela ainda funciona nesta versão, embora a abordagem de observadores seja a mais nova.

Detalhes

Descrição original do autor

Use when observing iii functions with iii.observe, writing filters, reacting to engine events, writing observable functions with owner delivery (onObserverAdded, obs.emit, obs.call), tuning local dispatch, or migrating from the deprecated registerTrigger / registerTriggerType across TypeScript, browser, Python, Rust, and Go.

repo: iii-hq/iii

Popularidade

Estrelas no GitHub
19 mil
Posição no ranking
#10496
Licença
—
Atualizada em
02/11/2026

Essa skill é útil?

0

Entre para votar.

Comentários

  • …

Mais skills deste repositório

Skills parecidas